Imports System
Imports System.Configuration
Imports MyClasses
Imports BAL
Imports DAL
Imports C1.Win.C1FlexGrid
Imports System.Text
Imports System.Drawing.Printing

Public Class frmSalePrint

#Region "Declaration"

    Public PrintBill As Byte
    Private DoctorID As Integer
    Private intCityCD As Integer
    Public IsBillSaved As Byte
    Public intSaleType As Integer
    Public intCounter As Integer                'Currently Selected Counter


    Dim tableFont, titlefont, headfont, tabletitlefont As Font
    Dim X1, X2, X3 As Integer
    Dim wi As Integer
    Dim PHi As Double
    Dim Y As Integer
    Dim intPrintNext As Integer = 1
    Dim pageWidth As Integer

    Dim FinalSize As Double
    Dim dobTotal As Double
    '<<
    Dim curY As Integer
    Dim Foot1 As String
    Dim Foot2 As String
    Dim Foot3 As String
    Dim PageNo As Integer = 1 'FOR SHOWING PAGE NO IN BILL
    '>>
    Private intTotalColumns As Integer = 25      'SALE ITEM'S NO OF COLUMNS   
    Private intCurrentRow As Integer = 1
    Private TotAmount As Double                  'USED TO SHOW TOTAL AMOUNT OF ACTIVE ITEMS  IN CURRENT COUNTER
    
    Private btStatus As Byte                     'CURRENT RECORD STATUS (0:CURRENT ROW IS NOT SAVED/INCOMPLETE      1:CURRENT RECORD DATA IS SAVED
    Private BtLoading As Byte                    'VARIABLE IS USED TO AVOID UNNECESSARY LOOPS/EVENTS/EXECUTION WHILE SETTING OR LOADING THE DATA                         

    Private strExistingItems As String

    Private intDelete As Integer                 'VARIABLE IS USED TO PASS THE VALUE FROM BEFORE DELETE ROW TO AFTER DELETE ROW FOR AMT CALCULATION PURPOSE(NO OF ROWS DELETED.)  
    Private intGrdCntRows As Integer = 31
    Public ItemsFromSale As C1.Win.C1FlexGrid.RowCollection
    Public ParentTop As Integer  'PARENT TOP IS SET FROM SALEFORM TO SHOWPRODUCTLIST IF FORM IS CALLED FROM SALEFORM
    Private btInSelectBatch As Byte          'Variable is used to avoid repetative call for the function SelectBatch()
    'Public frmListProducts As frmProducts
    '---------------------------------SOMETHING EXTRA --------------------------------------------------------'
    'Status Column of SaleGrid uses  : 1  "A"  -Active Items(not yet Saved or Freezed)
    '                                : 2  "F"  -Freeze Items(Temporary saved not saved under perticular Bill
    '                                : 3  "U"  -Record is updated on Screen & till not saved
    '                                : 4  "P"  -Used to Save & Print
    '                                : 5  "D"  -Deleted  
    '                                : 6  "W"  -Saved in Working table 
    '
    'Byte DataType used as boolean   : 1 --TRUE
    '                                : 0 --FALSE  
    '
    '---------------------------------FORM SHORTCUTS --------------------------------------------------------'
    '       
    '       CTRL + F                 :- FREEZE ITEMS
    '       CTRL + SHIFT + CounterNo :- SHIFT SELECTED ITEMS TO COUNTERNO
    '       CTRL + COUNTERNO         :- ACTIVATE COUNTER
    '       CTRL + F1                :- DISPLAY SHORTCUTS
    '       CTRL + S                 :- SAVE  SELECTED ITEMS(AGAINST COUNTER SALE) 
    '       CTRL + P                 :- PRINT SELECTED ITEMS 
    '       ALT  + S                 :- SAVE  ALL ITEMS(AGAINST COUNTER SALE) 
    '       ALT  + P                 :- PRINT ALL ACTIVE ITEMS
    '       ALT  + D                 :- DELETE SELECTED ITEMS
    '       ALT  + I                 :- SHOW PRODUCT LIST WHEN CURRENT ROW IS NOT SAVED (WHEN ACTIVE ONLY. OHTERWISE THE DELETE THE PRODUCT & SELECT THE NEW ITEM)
    '       ALT  + C                 :- CLOSE THE COUNTER SALE FORM
    '       ALT  + Y                 :- DISPLAY COUNTER SUMMARY
    '       ESC                      :- HIDE COUNTER SUMMARY OR SHORTCUT WINDOW

    '-------NSP :- apply this changes to New Sale Print 
    '
    '---------------------------------     CODE    --------------------------------------------------------'

    'CHANGTES TAKEN FROM SALE FORM ARE REMARKED AS 'NSP
#End Region '"DECLARATION"

#Region " Form( & control) Events"
    Private Sub txtDisPercent_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtDisPercent.KeyDown
        Try
            If e.Alt Then Exit Sub
            If e.KeyCode = Keys.Enter Then txtPaidAmt.Focus()
            If BCommon.ValidateText(txtDisPercent.Text, e.KeyCode, "NUM") = False Then
                e.SuppressKeyPress = True
            ElseIf e.Shift = True Then
                e.SuppressKeyPress = True
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, " txtDiscount_KeyDown")
        End Try
    End Sub

    Private Sub txtDisPercent_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtDisPercent.LostFocus
        Call SetDisc("P")
    End Sub

    Private Sub txtDiscount_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtDiscount.LostFocus
        Call SetDisc("A")
    End Sub
    Private Sub btnCnvtBill_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCnvtBill.Click
        Try
            If SaveData(False) > 0 Then
                Dim SaleBill As New frmSaleFinal
                With SaleBill
                    .StartPosition = FormStartPosition.Manual
                    .Height = MDIPharmacy.MdiScaleHeight
                    .Width = MDIPharmacy.MdiScaleWidth
                    Dim pt As New Point
                    .Size = Me.Size
                    pt.Y = ((MDIPharmacy.MdiScaleHeight - .Height) / 2) + MDIPharmacy.pnlHeading.Height + MDIPharmacy.MenuStrip.Height
                    pt.X = (MDIPharmacy.MdiScaleWidth - .Width) / 2
                    .Location = pt
                    .ShowInTaskbar = False
                    .intCustID = cmDCustomerName.SelectedValue
                    .ShowDialog(MDIPharmacy)
                End With
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "btnCnvtBill_Click")
        End Try
    End Sub

    Private Sub btnOkPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOkPrint.Click
        SaveData(False)
    End Sub

    Private Sub btnFnlbill_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnFnlbill.Click
        SaveData(True)
    End Sub

    Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
        Try
            IsBillSaved = 0
            Me.Close()
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "btnClose_Click")
        End Try
    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Try
            Dim strNewItems As String = GetNewAddedItems()
            If Trim(strNewItems) <> "" Then
                Dim intRow As Integer
                If DSale.DeleteItems(strNewItems) > 0 Then
                    Dim strItems() As String = strNewItems.Split(",")
                    With fgItems
                        For intCount As Integer = 0 To strItems.Length - 1
                            intRow = .FindRow(strItems(intCount), 1, 14, False, True, True)
                            If intRow > 0 Then .Rows.Remove(intRow)
                        Next
                        .Refresh()
                        Call CalculateAmt()
                        Call CalculteTotalAmt()
                        Call CalculateProfitAmt()
                    End With
                End If
            End If

        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "btnCancel_Click")
        End Try
    End Sub

    Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click
        Try
            Dim strDeleteItems As String = GetDeletedItems()
            If strDeleteItems <> String.Empty Then
                DSale.DeleteItems(strDeleteItems)
                Call ClearGridData()
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "btnClear_Click")
        End Try
    End Sub

    Private Sub ClearGridData()
        Try
            BtLoading = 0
            Me.fgItems.Rows.RemoveRange(1, Me.fgItems.Rows.Count - 1)
            Me.fgItems.Rows.Count = intGrdCntRows
            Me.txtBalance.Text = "0.00"
            Me.txtNetAmount.Text = "0.00"
            Me.txtDiscount.Text = "0.00"
            Me.txtTotal.Text = "0.00"
            Me.txtPaidAmt.Text = "0.00"
            Me.txtProfit.Text = "0.00"
            BtLoading = 0
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "ClearGridData")
        End Try
    End Sub

    Private Sub txtTax_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtTax.KeyDown
        Try
            If BCommon.ValidateText(e.KeyCode, "NUM", False) = False Then
                e.SuppressKeyPress = True
            ElseIf e.Shift = True Then
                e.SuppressKeyPress = True
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "txtTax_KeyDown")
        End Try
    End Sub

    Private Sub txtDiscount_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtDiscount.KeyDown
        Try
            If e.Alt Then Exit Sub
            If e.KeyCode = Keys.Enter Then txtPaidAmt.Focus()
            If BCommon.ValidateText(txtDiscount.Text, e.KeyCode, "NUM") = False Then
                e.SuppressKeyPress = True
            ElseIf e.Shift Then
                e.SuppressKeyPress = True
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, " txtDiscount_KeyDown")
        End Try

        'Try
        '    If e.Alt Then Exit Sub
        '    If e.KeyCode = Keys.Enter Then txtPaidAmt.Focus()
        '    If BCommon.ValidateText(e.KeyCode, "NUM", False) = False Then
        '        e.SuppressKeyPress = True
        '    ElseIf e.Shift = True Then
        '        e.SuppressKeyPress = True
        '    End If
        'Catch ex As Exception
        '    BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, " txtDiscount_KeyDown")
        'End Try
    End Sub

    Private Sub txtPaidAmt_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtPaidAmt.KeyDown
        If e.Alt Then Exit Sub
        Try
            'If BCommon.ValidateText(e.KeyCode, "NUM", False) = False Then
            '    e.SuppressKeyPress = True
            'ElseIf e.Shift = True Then
            '    e.SuppressKeyPress = True
            If e.Shift = True Then
                If (e.KeyCode >= 48 And e.KeyCode <= 48 + 10) Or (e.KeyCode >= 96 And e.KeyCode <= 96 + 10) Then
                    e.SuppressKeyPress = True : Exit Sub
                End If
            End If
            If BCommon.ValidateText(txtPaidAmt.Text, e.KeyCode, "NUM") = False Then e.SuppressKeyPress = True
            If e.KeyCode = Keys.Enter Then
                btnOkPrint.Focus()
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "txtPaidAmt_KeyDown")
        End Try
    End Sub

    Private Sub txtCredit_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtCredit.KeyDown
        If e.Alt Then Exit Sub
        Try
            If BCommon.ValidateText(e.KeyCode, "NUM", False) = False Then
                e.SuppressKeyPress = True
            ElseIf e.Shift = True Then
                e.SuppressKeyPress = True
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "txtCredit_KeyDown")
        End Try
    End Sub

    Private Sub txtDebit_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtDebit.KeyDown

        If e.Alt Then Exit Sub
        Try
            If BCommon.ValidateText(e.KeyCode, "NUM", False) = False Then
                e.SuppressKeyPress = True
            ElseIf e.Shift = True Then
                e.SuppressKeyPress = True
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "txtDebit_KeyDown")
        End Try
    End Sub

    Private Sub txtTax_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtTax.LostFocus
        Try
            GetCalculation()
            Call CalculateReturnAmt()
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "txtTax_LostFocus")
        End Try
    End Sub

    Private Sub txtPaid_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtPaidAmt.LostFocus
        Try
            If Trim(Me.txtPaidAmt.Text) = "" Then Me.txtPaidAmt.Text = "0.00"
            Call CalculateReturnAmt()
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "txtPaid_LostFocus")
        End Try
    End Sub

    Private Sub txtCredit_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtCredit.LostFocus
        Try
            '            GetCalculation()
            Call CalculateReturnAmt()
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "txtCredit_LostFocus")
        End Try
    End Sub

    Private Sub txtDebit_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtDebit.LostFocus
        Try
            GetCalculation()
            Call CalculateReturnAmt()
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "txtDebit_LostFocus")
        End Try
    End Sub

    Private Sub frmSalePrint_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyUp

        Try
            If e.Control = True Then
                If e.Alt = False Then
                    Select Case e.KeyCode
                        Case Keys.F1        'SHOW PRODUCTS
                            Call DisplayShortCuts("S")
                            'Case Keys.F         'FREEZE SELECTED ITEMS
                            '    Call FreezeItems("S")
                        Case Keys.I         '
                            Call showProductList(fgItems.Col)
                        Case Keys.P          'SHOW PROFIT
                            Call CalculateProfitAmt()
                    End Select
                End If
            ElseIf e.KeyCode = Keys.Escape Then 'HIDE SHORTCUTS OR COUNTER SUMMARY WINDOW
                DisplayShortCuts("H")
            ElseIf e.KeyCode = Keys.F1 Then
                e.SuppressKeyPress = True
                'Help.ShowHelp(Me, "Pharma.chm", HelpNavigator.KeywordIndex, "Regular Sale")
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "frmSalePrint_KeyUp")
        Finally

        End Try
    End Sub

    Private Sub frmSalePrint_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Try
            BtLoading = 0
            BCommon.SetFormStandards(Me)
            Call DisplayData()
            'frmListProducts.SetGrid()
            Dim strCurrancy = ConfigurationManager.AppSettings("Currency").ToString()
            Me.lblRs1.Text = strCurrancy
            Me.lblRs2.Text = strCurrancy
            Me.lblRs3.Text = strCurrancy
            Me.lblRs4.Text = strCurrancy
            Me.lblRs5.Text = strCurrancy
            'Divya@31/03/08 : Condition checked for User Customize Setting 
            If ConfigurationManager.AppSettings("SaleProfit") = "No" Then
                lblProLoss.Visible = False
                lblProfit.Visible = False
                txtProfit.Visible = False
            End If
            '>>End Divya
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "frmSalePrint_Load")
        End Try
    End Sub

    Private Sub cmDCustomerName_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles cmDCustomerName.KeyDown
        Try
            If e.Alt Then Exit Sub
            If e.KeyCode = Keys.Enter Then cmDDoctor.Focus()
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "cmDCustomerName_KeyDown")
        End Try
    End Sub

    Private Sub cmDCustomerName_SelectedValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmDCustomerName.SelectedValueChanged
        Dim dtDoctor As New DataTable
        Try
            If intSaleType = 3 Then
                If cmDCustomerName.SelectedIndex > 0 Then
                    'SETTING DOCTOR TO RESPECTIVE CUSTOMER
                    dtDoctor = DSalePrint.GetDoctor(cmDCustomerName.SelectedValue.ToString())
                    If dtDoctor.Rows.Count > 0 Then
                        Me.cmDDoctor.SelectedValue = dtDoctor.Rows(0).Item("DOCTORID")
                        Me.txtAddress.Text = dtDoctor.Rows(0).Item("DESCRIPTION")
                    End If
                End If
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "cmDCustomerName_SelectedValueChanged")
        End Try
    End Sub

    Private Sub cmDDoctor_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles cmDDoctor.KeyDown
        Try
            If e.Alt Then Exit Sub
            If e.KeyCode = Keys.Enter Then
                fgItems.Focus()
                fgItems.Col = 1
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "cmDDoctor_KeyDown")
        End Try
    End Sub

    Private Sub cmbTitle_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles cmbTitle.KeyDown
        Try
            If e.Alt Then
                Exit Sub
            ElseIf e.KeyCode = Keys.Enter Then
                cmDCustomerName.Focus()
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "cmbTitle_KeyDown")
        End Try

    End Sub


    Private Sub PrintDocument1_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
        Dim fmt As New StringFormat(StringFormatFlags.LineLimit)
        Dim fmtr As New StringFormat(StringFormatFlags.NoClip)
        Dim fmtalgin As New StringFormat(fmtr)

        Dim TextSize As New System.Drawing.SizeF
        ''Dim QtySize As New System.Drawing.SizeF
        Y = PrintDocument1.DefaultPageSettings.Margins.Top + 10
        curY = PrintDocument1.DefaultPageSettings.Margins.Top + 10
        Dim count As Integer = 0
        Dim intCount As Integer = 1
        Dim curRowHeight As Integer
        Dim FootStart As Integer
        ''Dim Xstart As New System.Drawing.SizeF
        Dim textWidth As New System.Drawing.SizeF
        'Dim Position As Integer
        'Dim intPrintNext As Integer = 1

        Try
            Call SetPageHeader(e) 'Setting the Header
            FootStart = PHi - GetFooterHeight(e) - PrintDocument1.DefaultPageSettings.Margins.Bottom
            For intCount = intPrintNext To fgItems.Rows.Count - 1
                If IsNothing(fgItems.Item(intCount, "ITEMNAME")) = False Then
                    TextSize = e.Graphics.MeasureString(fgItems.Item(intCount, "ITEMNAME").ToString(), tableFont)
                    curRowHeight = TextSize.Height
                    'DESC  +  COMP  +  EXP  + BATCH + QTY  + AMOUNT 
                    '  8   +    2   +   1.5   +   3   +   2  +   2

                    If FootStart > curY + curRowHeight Then
                        e.Graphics.DrawString(fgItems.Item(intCount, "ITEMNAME").ToString(), tableFont, Brushes.Black, DrawRectangelF(X1, curY, (wi * 8) - 2, curRowHeight), fmt)
                        'e.Graphics.DrawRectangle(Pens.Black, X1, curY, (wi * 8) - 2, curRowHeight)
                        e.Graphics.DrawString(fgItems.Item(intCount, "COMPANY").ToString(), tableFont, Brushes.Black, DrawRectangelF(X1 + (wi * 8), curY, (wi * 1.5) - 2, curRowHeight), fmt)
                        e.Graphics.DrawString(fgItems.Item(intCount, "EXPIRY").ToString(), tableFont, Brushes.Black, DrawRectangelF(X1 + (wi * 9.5), curY, (wi * 2) - 2, curRowHeight), fmt)
                        e.Graphics.DrawString(Trim(fgItems.Item(intCount, "CLRcode")), tableFont, Brushes.Black, DrawRectangelF(X1 + (wi * 11.5), curY, (wi * 3) - 2, curRowHeight), fmt)

                        'Xstart.Width = X1 + (wi * 15)
                        'textWidth.Width = (wi * 17) - 2
                        'TextSize = e.Graphics.MeasureString(fgItems.Item(intCount, "QTY").ToString(), tableFont)
                        'textWidth.Width = textWidth.Width - TextSize.Width - 10

                        'e.Graphics.DrawString(fgItems.Item(intCount, "QTY").ToString(), tableFont, Brushes.Black, DrawRectangelF(textWidth.Width, curY, TextSize.Width, curRowHeight), fmt)
                        'fmtr.Alignment = StringAlignment.Far
                        'fmtalgin.LineAlignment = StringAlignment.Center
                        fmtalgin.Alignment = StringAlignment.Far


                        e.Graphics.DrawString(fgItems.Item(intCount, "QTY").ToString(), tableFont, Brushes.Black, DrawRectangelF(X1 + (wi * 14.5), curY, (wi * 2) - 2, curRowHeight), fmtalgin)
                        'e.Graphics.DrawString(fgItems.Item(intCount, "QTY").ToString(), tableFont, Brushes.Black, DrawRectangelF((X1 + (wi * 15) + 10)-(), curY, (wi * 17) - 2, curRowHeight), fmt)
                        'e.Graphics.DrawRectangle(Pens.Black, X1 + (wi * 17), curY, (wi * 3) - 5, curRowHeight)
                        e.Graphics.DrawString(BCommon.CheckDecimal(fgItems.Item(intCount, "AMOUNT").ToString()), tableFont, Brushes.Black, DrawRectangelF(X1 + (wi * 16.5), curY, (wi * 3) - 5, curRowHeight), fmtalgin)

                        If IsNothing(fgItems.Item(intCount, "AMOUNT")) = False Then
                            dobTotal = dobTotal + Convert.ToDouble(fgItems.Item(intCount, "AMOUNT").ToString())
                        End If
                        count = count + 1
                        curY = curY + curRowHeight
                        e.HasMorePages = False
                        intPrintNext = 1
                    Else
                        e.HasMorePages = True
                        intPrintNext = intCount
                        curY = FootStart
                        Call SetPageFooter(e)   'Setting the Footer When Record goes to Next Page
                        PageNo = PageNo + 1
                        Exit For
                    End If
                Else
                    curY = FootStart
                    Call SetPageFooter(e)      'Setting the Footer When Record Available in One Page
                    PageNo = 1
                    Exit For
                End If
            Next
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "PrintDocument1_PrintPage")
        End Try

    End Sub

    Private Function DrawRectangelF(ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer) As RectangleF
        Try
            Dim drawRect As New RectangleF(x, y, width, height)
            Return drawRect
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "DrawRectangelF")
        End Try
    End Function

    Private Sub StripTimer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles StripTimer.Tick

        Try
            lblStrip.Left -= 4
            If lblStrip.Left + lblStrip.Width < 0 Then
                lblStrip.Left = Me.Width
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "StripTimer_Tick")
        End Try
    End Sub
#End Region

#Region "GRID SETTINGS"

    Private Sub SetGrids()
        Try
            'ITEM DISPLAY GRID
            With fgItems
                .Left = grpheader.Left
                .Width = grpheader.Width
                .AllowDelete = True
                .Rows.Count = 30
                .Cols.Fixed = 0
                .Cols.Count = intTotalColumns
                .ScrollBars = ScrollBars.None
                .AllowAddNew = False
                .SelectionMode = SelectionModeEnum.ListBox

                Call SetGridCaptions()

                'HIDDEN COLUMNS
                .Cols("ITEMID").Visible = False
                .Cols("LOCATION").Visible = False
                .Cols("SCHEMEID").Visible = False
                .Cols("STATUS").Visible = False
                .Cols("EXPIRY").Visible = False
                .Cols("PURCHASEPRICE").Visible = False
                .Cols("SEQID").Visible = False
                .Cols("BATCHQTY").Visible = False
                .Cols("SCHEDULEDRUG").Visible = False
                .Cols("EMERGENCYSTOCK").Visible = False
                .Cols("TOTALSTOCK").Visible = False
                .Cols("STOCKDETAILS").Visible = False
                .Cols("ISMULTIBATCH").Visible = False
                .Cols("SCHEMESTOCK").Visible = False
                .Cols("MAXRATE").Visible = False
                .Cols("TAX").Visible = False

                'NON EDITABLE COLUMNS 
                .Cols("CODE").AllowEditing = False
                .Cols("ITEMNAME").AllowEditing = False
                .Cols("COMPANY").AllowEditing = False
                .Cols("LOCATION").AllowEditing = False
                .Cols("CLRcode").AllowEditing = False
                .Cols("AMOUNT").AllowEditing = False

                'NUMBERS ONLY COLUMN
                .Cols("QTY").DataType = System.Type.GetType("System.Int32")
                .Cols("RATE").DataType = System.Type.GetType("System.Double")
                .Cols("AMOUNT").DataType = System.Type.GetType("System.Decimal")
                .Cols("MAXRATE").DataType = System.Type.GetType("System.Decimal")
                .Cols("TAX").DataType = System.Type.GetType("System.Decimal")

                .Cols("RATE").Format = "0.00"
                .Cols("AMOUNT").Format = "0.00"
                .Cols("MAXRATE").Format = "0.00"
                .Cols("TAX").Format = "0.00"

                .Cols("SCHEMEID").DataType = System.Type.GetType("MyClasses.CScheme")

                'COLOR SETTINGS 
                .Styles.Normal.TextEffect = C1.Win.C1FlexGrid.TextEffectEnum.Raised
                .Styles.Alternate.TextEffect = C1.Win.C1FlexGrid.TextEffectEnum.Raised

                'COLUMN'S TEXT ALIGNMENT
                .Cols("CODE").TextAlign = C1.Win.C1FlexGrid.TextAlignEnum.CenterCenter
                .Cols("ITEMNAME").TextAlign = C1.Win.C1FlexGrid.TextAlignEnum.LeftCenter
                .Cols("CLRcode").TextAlign = C1.Win.C1FlexGrid.TextAlignEnum.LeftCenter
            End With

            'BATCH DISPLAY GRID
            With fgBatch
                .Cols.Count = 5
                .Styles.Normal.TextEffect = C1.Win.C1FlexGrid.TextEffectEnum.Raised
                .Styles.Alternate.TextEffect = C1.Win.C1FlexGrid.TextEffectEnum.Raised
            End With

        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "SetGrids")
        End Try
    End Sub

    Private Sub SetColumnWidths()
        Dim intGridWidth As Integer = fgItems.Width - 5

        Try
            With fgItems
                .Cols("ITEMID").Width = 0                       'Hidden Column         
                .Cols("CODE").Width = intGridWidth / 12
                .Cols("ITEMNAME").Width = intGridWidth / 9 * 3
                .Cols("COMPANY").Width = intGridWidth / 11
                .Cols("LOCATION").Width = 0                    'intGridWidth / 11   
                .Cols("SCHEMEID").Width = 0                    'Hidden Column   
                .Cols("SCHEME").Width = intGridWidth / 11
                .Cols("CLRcode").Width = intGridWidth / 11
                .Cols("QTY").Width = intGridWidth / 11
                .Cols("RATE").Width = intGridWidth / 11
                .Cols("AMOUNT").Width = intGridWidth / 11
                .Cols("STATUS").Width = 0                    'Hidden Column     
                .Cols("EXPIRY").Width = 0                    'Hidden Column     
                .Cols("PURCHASEPRICE").Width = 0             'Hidden Column
                .Cols("SEQID").Width = 0                     'Hidden Column       
                .Cols("BATCHQTY").Width = 0                  'Hidden Column     
                .Cols("CONVERSIONUNIT").Width = 0            'Hidden Column
                .Cols("SCHEDULEDRUG").Width = 0              'Hidden Column  
                .Cols("EMERGENCYSTOCK").Width = 0            'Hidden Column 
                .Cols("TOTALSTOCK").Width = 0                'Hidden Column     
                .Cols("STOCKDETAILS").Width = 0              'Hidden Column   
                .Cols("ISMULTIBATCH").Width = 0              'Hidden Column   
                .Cols("SCHEMESTOCK").Width = 0               'Hidden Column   
                .Cols("MAXRATE").Width = 0                   'Hidden Column   
                .Cols("TAX").Width = 0                       'Hidden Column   
                .ExtendLastCol = True     'EXTENDS LAST COLUMN UPTO REMAINED COLUMN WIDTH 
            End With

        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "SetColumnWidths")
        End Try
    End Sub

    Private Sub SetGridCaptions()
        Try
            With fgItems
                'SET COLUMN NAMES
                .Cols(0).Name = "ITEMID"
                .Cols(1).Name = "CODE"
                .Cols(2).Name = "ITEMNAME"
                .Cols(3).Name = "COMPANY"
                .Cols(4).Name = "LOCATION"
                .Cols(5).Name = "SCHEMEID"
                .Cols(6).Name = "CLRcode"
                .Cols(7).Name = "SCHEME"
                .Cols(8).Name = "QTY"
                .Cols(9).Name = "RATE"
                .Cols(10).Name = "AMOUNT"
                .Cols(11).Name = "STATUS"
                .Cols(12).Name = "EXPIRY"
                .Cols(13).Name = "PURCHASEPRICE"
                .Cols(14).Name = "SEQID"
                .Cols(15).Name = "BATCHQTY"
                .Cols(16).Name = "CONVERSIONUNIT"
                .Cols(17).Name = "SCHEDULEDRUG"
                .Cols(18).Name = "EMERGENCYSTOCK"
                .Cols(19).Name = "TOTALSTOCK"
                .Cols(20).Name = "STOCKDETAILS"
                .Cols(21).Name = "ISMULTIBATCH"
                .Cols(22).Name = "SCHEMESTOCK"
                .Cols(23).Name = "MAXRATE"
                .Cols(24).Name = "TAX"

                'SET COLUMN CAPTIONS
                .Cols("ITEMID").Caption = "ItemID"
                .Cols("CODE").Caption = "Code"
                .Cols("ITEMNAME").Caption = "ItemName"
                .Cols("COMPANY").Caption = "Company"
                .Cols("LOCATION").Caption = "Location"
                .Cols("SCHEMEID").Caption = "SCHEMEID"
                .Cols("SCHEME").Caption = "Scheme"
                .Cols("CLRcode").Caption = "Batch No."
                .Cols("QTY").Caption = "Qty"
                .Cols("RATE").Caption = "Price"
                .Cols("AMOUNT").Caption = "Amount"
                .Cols("STATUS").Caption = "Status"
                .Cols("EXPIRY").Caption = "Expiry"
                .Cols("PURCHASEPRICE").Caption = "Purchase Price"
                .Cols("SEQID").Caption = "SEQ ID"
                .Cols("BATCHQTY").Caption = "Batch Qty"
                .Cols("CONVERSIONUNIT").Caption = "Conversion Unit"
                .Cols("SCHEDULEDRUG").Caption = "ScheduleDrug"
                .Cols("EMERGENCYSTOCK").Caption = "EmergencyStock"
                .Cols("TOTALSTOCK").Caption = "TotalStock"
                .Cols("STOCKDETAILS").Caption = "STOCKDETAILS"
                .Cols("ISMULTIBATCH").Caption = "ISMULTIBATCH"
                .Cols("SCHEMESTOCK").Caption = "SCHEMESTOCK"
                .Cols("TAX").Caption = "TAX APPLIED"
            End With
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "SetGridCaption")
        End Try
    End Sub

#End Region '"GRID SETTINGS"

#Region "GRID EVENT FUNCTIONS"

    Private Sub fgItems_BeforeDeleteRow(ByVal sender As Object, ByVal e As C1.Win.C1FlexGrid.RowColEventArgs) Handles fgItems.BeforeDeleteRow
        Try
            With fgItems
                If IsNothing(.Item(e.Row, "ITEMID")) OrElse Trim(.Item(e.Row, "ITEMID")) = "" Then
                    e.Cancel = True
                ElseIf .Item(e.Row, "STATUS") = "A" Then
                    intDelete += 1
                    DisplayShedule("", "")
                    ClearItemInfo()
                    btStatus = 1
                Else
                    If DSale.DeleteItems(.Item(e.Row, "SEQID")) <= 0 Then
                        e.Cancel = True
                    Else
                        If .Item(e.Row, "STATUS") = "W" Then intDelete += 1
                    End If
                End If
            End With
            Call CalculteTotalAmt()
            Call CalculateProfitAmt()
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "fgItems_BeforeDeleteRow")
        End Try
    End Sub

    Private Sub fgItems_AfterDeleteRow(ByVal sender As Object, ByVal e As C1.Win.C1FlexGrid.RowColEventArgs) Handles fgItems.AfterDeleteRow
        Try
            If intDelete > 0 Then
                intDelete = 0
            End If
            Call CalculteTotalAmt()
            Call CalculateProfitAmt() 'Modified By:-VINIT(2008/01/22)
            'CalculateAmt()
            fgItems.Refresh()
            If fgItems.Rows.Count < intGrdCntRows Then fgItems.Rows.Count = intGrdCntRows

        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "fgItems_AfterDeleteRow")
        End Try
    End Sub

    Private Sub fgItems_AfterRowColChange(ByVal sender As Object, ByVal e As C1.Win.C1FlexGrid.RangeEventArgs) Handles fgItems.AfterRowColChange
        Try
            If BtLoading = 0 Then Exit Sub
            If e.NewRange.r1 > e.OldRange.r1 AndAlso fgItems.Row = fgItems.Rows.Count - 5 Then fgItems.Rows.Count += 5
            intCurrentRow = fgItems.Row
            If e.NewRange.r1 <> e.OldRange.r1 Then lblInfo12.Visible = False
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "fgItems_AfterRowColChange")
        End Try
    End Sub

    Private Sub fgItems_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles fgItems.Click
        Try
            With fgItems
                If .Cols("CODE").Index = .MouseCol Or .Cols("ITEMNAME").Index = .MouseCol Then
                    showProductList(.MouseCol)
                End If
            End With
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "fgItems_Click")
        End Try
    End Sub

    Private Sub fgItems_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles fgItems.DoubleClick
        Try
            With fgItems
                If .Cols("CODE").Index = .MouseCol Or .Cols("ITEMNAME").Index = .MouseCol Then
                    showProductList(.MouseCol)
                End If
            End With
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "fgItems_DoubleClick")
        End Try
    End Sub

    Private Sub fgItems_EnterCell(ByVal sender As Object, ByVal e As System.EventArgs) Handles fgItems.EnterCell
        If BtLoading = 0 Then Exit Sub
        Try
            With fgItems
                If intCurrentRow = 0 Then Exit Sub
                If .RowSel < 0 OrElse .Row < 0 Then Exit Sub
                If .RowSel > 1 Then
                    If .Item(.RowSel - 1, "ITEMID") = Nothing OrElse .Item(.RowSel - 1, "ITEMID").ToString() = "" Then Exit Sub
                End If

                If .Rows(.Row).AllowEditing = False Then Exit Sub
                If .RowSel = .Rows.Count - 1 Then .Rows.Count = .Rows.Count + 10 'INCREMENTS NO OF ROWS BY 10 IF REACHED TO LAST ROW 
                Select Case .Col
                    Case .Cols("ITEMNAME").Index
                        If IsNothing(.Item(.Row, .Col)) OrElse Trim(.Item(.Row, .Col)) = "" Then Call showProductList(.Col)

                    Case .Cols("CLRcode").Index
                        If Not (.Item(.RowSel, "ITEMID") = Nothing OrElse .Item(.RowSel, "ITEMID").ToString() = "") Then
                            If IsNothing(.Item(.RowSel, "CLRcode")) OrElse Trim(.Item(.RowSel, "CLRcode")) = "" Then showBatchDetails()
                        End If
                End Select
            End With
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "fgItems_EnterCell")
        End Try
    End Sub

    Private Sub fgBatch_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles fgBatch.LostFocus
        Try
            SelectBatch()
            fgBatch.Visible = False
            fgItems.Focus()
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "fgBatch_LostFocus")
        End Try
    End Sub

    Private Sub fgBatch_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles fgBatch.KeyDown
        Try
            If e.KeyCode = Keys.Enter Then Call SelectBatch() : Exit Sub
            If e.KeyCode = Keys.Escape Then fgBatch.Visible = False
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "fgBatch_KeyDown")
        End Try
    End Sub

    Private Sub fgBatch_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles fgBatch.DoubleClick
        Call SelectBatch()
    End Sub

    Private Sub fgItems_ValidateEdit(ByVal sender As Object, ByVal e As C1.Win.C1FlexGrid.ValidateEditEventArgs) Handles fgItems.ValidateEdit

        If BtLoading = 0 Then Exit Sub
        Try
            With fgItems
                Select Case e.Col
                    Case .Cols("RATE").Index
                        If .Editor.Text <> "" AndAlso IsNumeric(.Editor.Text) Then
                            If Convert.ToDouble(.Editor.Text.ToString()) <= 0 Then
                                BCommon.ShowMsgError(10320) 'PLEASE ENTER VALID SALE RATE
                                e.Cancel = True
                                Exit Sub
                            Else
                                If CDbl(.Editor.Text) < CDbl(.Item(.RowSel, "PURCHASEPRICE")) Then
                                    BCommon.ShowMsgError(10231)
                                    .Cols("RATE").Item(.Row) = CDbl(.Item(.RowSel, "PURCHASEPRICE"))
                                    e.Cancel = True
                                    Exit Sub
                                ElseIf CDbl(.Editor.Text) > CDbl(.Item(.RowSel, "MAXRATE")) Then
                                    If BCommon.ShowMsgError(10418, "YN") = Windows.Forms.DialogResult.No Then
                                        .Cols("RATE").Item(.Row) = CDbl(.Item(.RowSel, "MAXRATE"))
                                        e.Cancel = True
                                        Exit Sub
                                    Else : .Item(.RowSel, "RATE") = .Editor.Text

                                    End If
                                Else : .Item(.RowSel, "RATE") = .Editor.Text
                                End If
                            End If
                        Else
                            BCommon.ShowMsgError(10239) 'PLEASE ENTER ONLY NUMERIC VALUES.
                            e.Cancel = True
                            .Editor.Text = ""
                            Exit Sub
                        End If
                        btStatus = 1
                        Call CalculateProfitAmt()
                        Call CalculateAmt()
                        If fgItems.Item(fgItems.RowSel, "STATUS") = "F" Then
                            fgItems.Item(fgItems.RowSel, "STATUS") = "U"
                        End If
                    Case .Cols("QTY").Index
                        '19 .TOTAL STOCK
                        '18 .EMERGENCY STOCK
                        '15 .BATCH QUANTITY
                        If .Editor.Text <> "" AndAlso IsNumeric(.Editor.Text) Then
                            If Convert.ToDouble(.Editor.Text.ToString()) < 1 Then
                                BCommon.ShowMsgError(10232)
                                e.Cancel = True
                                Exit Sub
                            End If
                        Else : BCommon.ShowMsgError(10239) 'PLEASE ENTER ONLY NUMERIC VALUES.
                            e.Cancel = True
                            Exit Sub
                        End If
                        btStatus = 1

                        Dim Qty As Integer = IIf(Trim(.Editor.Text) = "", 0, .Editor.Text)
                        Select Case .Item(.Row, "STATUS") 'Status
                            Case "A"
lblAutoInsert:
                                Dim BatchQty As Integer = IIf(Trim(.Item(.Row, "BATCHQTY")) = "", 0, .Item(.Row, "BATCHQTY"))
                                Dim TotalQty As Integer = IIf(Trim(.Item(.Row, "TOTALSTOCK")) = "", 0, .Item(.Row, "TOTALSTOCK"))
                                If Qty > BatchQty Then
                                    If Qty > TotalQty Then             'ASK FOR DUMMY PURCHASE 
                                        'If (MessageBox.Show(BCommon.GetMessage(10260), ConfigurationManager.AppSettings("MsgTitle"), MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes) Then
                                        If BCommon.ShowMsgError(10260, "YN") = Windows.Forms.DialogResult.Yes Then
                                            'Dim FrmTmpPurchase As New frmSaleWithoutStock
                                            'With FrmTmpPurchase
                                            '    .ItemID = fgItems.Item(fgItems.Row, "ITEMID")
                                            '    .ItemName = fgItems.Item(fgItems.Row, "ITEMNAME")
                                            '    .ShowDialog()
                                            '    If .btResult = 1 Then ' DUMMY PURCHASE IS DONE 
                                            '        BtLoading = 0
                                            '        fgItems.Item(fgItems.Row, "TOTALSTOCK") = DItem.GetStockQty(.ItemID)
                                            '        fgItems.Item(fgItems.Row, "BATCHQTY") = DItem.GetStockQty(.ItemID, fgItems.Item(fgItems.Row, "CLRcode"))
                                            '        If DStock.GetStockBatchs(fgItems.Item(fgItems.RowSel, "ITEMID")).Rows.Count > 0 Then
                                            '            fgItems.Item(fgItems.Row, "ISMULTIBATCH") = 1
                                            '        Else
                                            '            fgItems.Item(fgItems.Row, "ISMULTIBATCH") = 0
                                            '        End If
                                            '        BtLoading = 1
                                            '        showBatchDetails()
                                            '        'GoTo lblAutoInsert
                                            '        Exit Sub
                                            '    Else : e.Cancel = True  'IF DUMMY PURCHASE IS NOT DONE THEN CANCEL THE ENTERED QUANTITY
                                            '    End If
                                            'End With
                                        Else : e.Cancel = True
                                            .Editor.Text = BatchQty
                                        End If
                                    ElseIf .Item(.Row, "ISMULTIBATCH") = 1 Then    'IS ITEM CONTAINS MULTIPLE BATCHES STOCK
                                        'AUTO INSERT BATCH QUANTITY TO FULLFILL TOTAL QTY.
                                        '-----------------AUTO INSERT ITEM ----------------------
                                        BtLoading = 0  'SET VARIABLE THAT DATA IS LOADING TO, NOT FIRE THE GRID EVENTS
                                        Dim intStartRow As Integer = .Row

                                        '1. FILL THE CURRENT BATCH STOCK FOR CURRENT ROW
                                        .Item(.Row, "QTY") = BatchQty
                                        .Editor.Text = BatchQty
                                        Qty -= BatchQty

                                        '2. SAVE CURRENT ROW
                                        SaveCurrentItem(intStartRow)
                                        '3. GET NEXT BATCHES
                                        'Dim dtbBatchDetails As DataTable = fgBatch.DataSource ' DStock.GetStockBatchs(.Item(.RowSel, "ITEMID")) 'GET BATCHWISE STOCK

                                        'dtbBatchDetails:-COLUMNS:- BATCH,EXPIRY,STOCK ,SALEPRICE,CONVERSIONFACTOR,PURCHASEPRICE
                                        Dim intCount As Integer = 1
                                        Dim intBatchRow As Integer = 1
                                        While Qty > 0

                                            '4. COPY FIRST ROW TO NEXT ROW
                                            Call CopyItemRow(intStartRow, intStartRow + intCount)

                                            '5. CHECK IF CURRENT BATCH IS SELECTED BATCH THEN MOVE TO NEXT BATCH DETAILAS
                                            If intBatchRow = fgBatch.Row Then intBatchRow += 1

                                            '6. FILL REMAINING DETAILS
                                            .Item(intStartRow + intCount, "CLRcode") = fgBatch.Rows(intBatchRow).Item(0) '"Batch No."
                                            .Item(intStartRow + intCount, "RATE") = BCommon.FormatAmount(fgBatch.Rows(intBatchRow).Item(3) / fgBatch.Rows(intBatchRow).Item(4)) '"Rate"
                                            .Item(intStartRow + intCount, "RATE") = CDbl(fgBatch.Item(intBatchRow, "SALEPRICE") / fgBatch.Item(intBatchRow, "CONVERSIONFACTOR"))
                                            .Item(intStartRow + intCount, "EXPIRY") = fgBatch.Rows(intBatchRow).Item(1) '"Expiry"
                                            .Item(intStartRow + intCount, "PURCHASEPRICE") = fgBatch.Rows(intBatchRow).Item(5) '"Purchase Price"
                                            .Item(intStartRow + intCount, "BATCHQTY") = fgBatch.Rows(intBatchRow).Item(2) '"Batch Qty"
                                            .Item(intStartRow + intCount, "CONVERSIONUNIT") = fgBatch.Rows(intBatchRow).Item(4) '"Conversion Unit"

                                            .Item(intStartRow + intCount, "PURCHASEPRICE") = CDbl(fgBatch.Item(intBatchRow, "PURCHASEPRICE") / fgBatch.Item(intBatchRow, "CONVERSIONFACTOR"))

                                            'SET SCHEME IF ANY
                                            Dim DefaultScheme As New CScheme
                                            If fgBatch.Item(intBatchRow, "SCHEMEID") > 0 Then  'IF SCHEME IS PRESENT TO THIS ITEM
                                                Dim ItemScheme As CScheme = BScheme.GetScheme(fgBatch.Item(intBatchRow, "SCHEMEID"))
                                                If Not IsNothing(ItemScheme) Then
                                                    .Item(.RowSel, "SCHEMEID") = ItemScheme
                                                    .Item(intStartRow + intCount, "SCHEMESTOCK") = fgBatch.Item(intBatchRow, "SCHEMEITEMQTY")
                                                    .Item(intStartRow + intCount, "SCHEME") = ItemScheme.GetSchemeName
                                                Else
                                                    .Item(intStartRow + intCount, "SCHEMEID") = DefaultScheme
                                                    .Item(intStartRow + intCount, "SCHEMESTOCK") = 0
                                                End If
                                            Else
                                                .Item(intStartRow + intCount, "SCHEMEID") = DefaultScheme
                                                .Item(intStartRow + intCount, "SCHEMESTOCK") = 0
                                            End If

                                            'SET TAX IF IT IS

                                            If BCommon.GetConfigValues("TAX") = 1 Then 'TAX IS APPLICABLE
                                                .Item(intStartRow + intCount, "TAX") = Math.Round((.Item(intStartRow + intCount, "RATE") * BTax.GetSaleTaxValue(.Item(intStartRow + intCount, "ITEMID"), fgBatch.Item(intBatchRow, "BATCH")) / 100), 2)
                                                .Item(intStartRow + intCount, "RATE") += .Item(intStartRow + intCount, "TAX")
                                                .Item(intStartRow + intCount, "MAXRATE") = CDbl(fgBatch.Item(intBatchRow, "MRP") / fgBatch.Item(intBatchRow, "CONVERSIONFACTOR")) + .Item(intStartRow + intCount, "TAX")
                                            Else 'TAX IS NOT APPLICABLE
                                                .Item(intStartRow + intCount, "TAX") = 0
                                                .Item(intStartRow + intCount, "MAXRATE") = CDbl(fgItems.Item(intStartRow + intCount, "MRP") / fgBatch.Item(intBatchRow, "CONVERSIONFACTOR"))
                                            End If

                                            '7. SET QUANTITY
                                            If fgBatch.Rows(intBatchRow).Item(2) >= Qty Then
                                                .Item(intStartRow + intCount, "QTY") = Qty '"Qty"
                                                Qty = 0
                                            Else : Qty = Qty - fgBatch.Rows(intBatchRow).Item(2)
                                                .Item(intStartRow + intCount, "QTY") = fgBatch.Rows(intBatchRow).Item(2)
                                            End If
                                            SetItemAmount(intStartRow + intCount)

                                            '8. SAVE CURRENT ROW
                                            SaveCurrentItem(intStartRow + intCount)

                                            '9. UPDATE VARIABLES DETAILS
                                            intCount += 1
                                            intBatchRow += 1
                                        End While
                                        BtLoading = 1
                                    End If
                                ElseIf Trim(.Item(.Row, "EMERGENCYSTOCK")) <> "" AndAlso .Item(.Row, "EMERGENCYSTOCK") > 0 AndAlso DItem.GetItemStock(.Item(.Row, "ITEMID")) - .Item(.Row, "QTY") < .Item(.Row, "EMERGENCYSTOCK") AndAlso BCommon.GetConfigValues("EMERGSTOCKALERT") = "Y" Then
                                    If MessageBox.Show(BCommon.GetMessage(10251).Replace("QTY", IIf(Trim(.Item(.Row, "EMERGENCYSTOCK")) = "", 0, .Item(.Row, "EMERGENCYSTOCK"))), ConfigurationManager.AppSettings("MsgTitle"), MessageBoxButtons.YesNo) = Windows.Forms.DialogResult.No Then
                                        .Editor.Text = 0
                                    End If
                                Else
                                    .Item(.Row, "QTY") = .Editor.Text
                                    If .Item(.Row, "SCHEMESTOCK") > 0 Then .Item(.Row, "SCHEME") = GetSchemeQty(.Row, Qty)
                                End If
                                btStatus = 1

                            Case "W", "F"
                                Dim workingStock As Integer = DItem.GetWorkingStock(.Item(.Row, "SEQID"))
                                If Qty <> workingStock Then
                                    Dim BatchQuantity As Integer = CInt(DItem.GetBatchItemStock(Trim(.Item(.Row, "ITEMID")), Trim(.Item(.Row, "CLRcode")))) + workingStock
                                    If Qty > BatchQuantity Then  'GETTOTALSTOCK FOR ITEM
                                        MessageBox.Show(BCommon.GetMessage(10307).Replace("QTY", IIf(BatchQuantity = Nothing, 0, BatchQuantity)), ConfigurationManager.AppSettings("MsgTitle")) 'Available Stock isOnly
                                        .Editor.Text = BatchQuantity
                                    ElseIf Trim(.Item(.Row, "EMERGENCYSTOCK")) <> "" AndAlso .Item(.Row, "EMERGENCYSTOCK") > 0 AndAlso DItem.GetItemStock(.Item(.Row, "ITEMID")) + workingStock - Qty < .Item(.Row, "EMERGENCYSTOCK") Then
                                        If MessageBox.Show(BCommon.GetMessage(10251).Replace("QTY", IIf(Trim(.Item(.Row, "EMERGENCYSTOCK")) = "", 0, Trim(.Item(.Row, "EMERGENCYSTOCK")))), ConfigurationManager.AppSettings("MsgTitle"), MessageBoxButtons.YesNo) = Windows.Forms.DialogResult.No Then
                                            .Editor.Text = 0
                                        End If
                                    End If
                                End If
                                .Item(.Row, "QTY") = .Editor.Text
                                If .Item(.Row, "SCHEMESTOCK") > 0 Then .Item(.Row, "SCHEME") = GetSchemeQty(.Row, .Editor.Text)
                                .Item(.Row, "STATUS") = "U"
                                btStatus = 1
                            Case "U"
                                Dim workingStock As Integer = DItem.GetWorkingStock(.Item(.Row, "SEQID"))
                                If Qty > workingStock Then
                                    Dim BatchQuantity As Integer = DItem.GetBatchItemStock(.Item(.Row, "ITEMID"), .Item(.Row, "CLRcode")) + workingStock
                                    If Qty > BatchQuantity Then     '15 BATCHQUANTITY
                                        'GETTOTALSTOCK FOR ITEM
                                        MessageBox.Show(BCommon.GetMessage(10307).Replace("QTY", IIf(Trim(.Item(.Row, "BATCHQTY")) = "", 0, .Item(.Row, "BATCHQTY"))), ConfigurationManager.AppSettings("MsgTitle")) 'Available Stock isOnly
                                        .Editor.Text = BatchQuantity
                                    ElseIf Trim(.Item(.Row, "EMERGENCYSTOCK")) <> "" AndAlso .Item(.Row, "EMERGENCYSTOCK") > 0 AndAlso DItem.GetItemStock(.Item(.Row, "ITEMID")) + workingStock - Qty < .Item(.Row, "EMERGENCYSTOCK") Then
                                        If MessageBox.Show(BCommon.GetMessage(10251).Replace("QTY", IIf(Trim(.Item(.Row, "EMERGENCYSTOCK")) = "", 0, .Item(.Row, "EMERGENCYSTOCK"))), ConfigurationManager.AppSettings("MsgTitle"), MessageBoxButtons.YesNo) = Windows.Forms.DialogResult.No Then
                                            .Editor.Text = 0
                                        End If
                                    End If
                                ElseIf .Item(.Row, "SCHEMESTOCK") > 0 Then
                                    .Item(.Row, "SCHEME") = GetSchemeQty(.Row, Qty)
                                End If
                                .Item(.Row, "QTY") = .Editor.Text
                                btStatus = 1
                        End Select
                        Call CalculateAmt()
                    Case .Cols("SCHEME").Index
                        '1.CHECK FOR VALID OR APPLICABLE SCHEME QUANTITY 
                        '  IF ENTERED SCHEME QUANTITY IS GREATER THANT APPLICABLE QTY THEN ONLY FIRE WARNING MESSAGE 
                        '2.CHECK FOR AVAILABLE SCHEME STOCK
                        Dim Qty As Integer = .Editor.Text
                        Dim ApplicableQty As Integer = GetSchemeQty(.Row, .Item(.Row, "QTY"))
                        If Qty > ApplicableQty Then
                            MessageBox.Show(BCommon.GetMessage(10308).Replace("QTY", ApplicableQty), ConfigurationManager.AppSettings("MsgTitle")) 'Eg. Applicable Schem Quantity is 4 Only.
                            .Editor.Text = ApplicableQty
                        ElseIf Qty > .Item(.Row, "SCHEMESTOCK") Then
                            MessageBox.Show(BCommon.GetMessage(10306).Replace("QTY", .Item(.Row, "SCHEMESTOCK")), ConfigurationManager.AppSettings("MsgTitle")) 'ONLY 10 OR ..  SCHEME ITEM QUANTITY IS AVAILBALE.
                            .Editor.Text = .Item(.Row, "SCHEMESTOCK")
                        End If
                        btStatus = 1
                        If fgItems.Item(fgItems.RowSel, "STATUS") = "F" Then fgItems.Item(fgItems.RowSel, "STATUS") = "U"
                End Select
            End With
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "fgItems_ValidateEdit")
        End Try
    End Sub

    Private Sub fgItems_BeforeEdit(ByVal sender As Object, ByVal e As C1.Win.C1FlexGrid.RowColEventArgs) Handles fgItems.BeforeEdit
        Try
            With fgItems
                Select Case e.Col
                    Case .Cols("ITEMID").Index
                        e.Cancel = True
                    Case .Cols("CODE").Index
                        e.Cancel = True
                    Case .Cols("ITEMNAME").Index
                        e.Cancel = True
                    Case .Cols("CLRcode").Index
                        e.Cancel = True
                    Case .Cols("SCHEME").Index

                        If IsNothing(fgItems.Item(fgItems.Row, "SCHEMEID")) Then
                            e.Cancel = True
                        ElseIf CType(fgItems.Item(fgItems.Row, "SCHEMEID"), CScheme).SchemeType <> "F" Then
                            e.Cancel = True
                        End If
                    Case .Cols("QTY").Index
                        If IsNothing(fgItems.Item(fgItems.Row, "ITEMID")) OrElse Trim(fgItems.Item(fgItems.Row, "ITEMID")) = "" Then e.Cancel = True
                    Case .Cols("RATE").Index
                        If IsNothing(fgItems.Item(fgItems.Row, "ITEMID")) OrElse Trim(fgItems.Item(fgItems.Row, "ITEMID")) = "" Then e.Cancel = True
                End Select
            End With
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "fgItems_BeforeEdit")
        End Try
    End Sub

    Private Sub fgItems_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles fgItems.KeyUp
        Try
            With fgItems
                If (fgItems.Col = fgItems.Cols("CODE").Index OrElse fgItems.Col = fgItems.Cols("ITEMNAME").Index) Then
                    If e.KeyCode = Keys.Space Then
                        showProductList(fgItems.Col)
                    ElseIf e.KeyCode = Keys.Space OrElse (e.KeyCode >= Keys.A And e.KeyCode <= Keys.Z) Then
                        showProductList(fgItems.Col, e.KeyData.ToString())
                    End If
                ElseIf fgItems.Col = fgItems.Cols("CLRcode").Index AndAlso e.KeyCode = Keys.Space Then
                    Call showBatchDetails()
                End If
            End With
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "fgItems_KeyUp")
        End Try
    End Sub

    Private Sub fgItems_SetupEditor(ByVal sender As Object, ByVal e As C1.Win.C1FlexGrid.RowColEventArgs) Handles fgItems.SetupEditor
        Try
            If e.Col = fgItems.Cols("QTY").Index Then
                Dim ctl As Control = fgItems.Editor
                CType(ctl, TextBox).MaxLength = 5
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "fgItems_SetupEditor")
        End Try
    End Sub

    Private Sub fgItems_BeforeRowColChange(ByVal sender As Object, ByVal e As C1.Win.C1FlexGrid.RangeEventArgs) Handles fgItems.BeforeRowColChange
        '1  WRITE CODE  FOR ROWCHANGE ONLY 
        '2  IF ROW IS CHANGED THEN CHECK IS ALL ENTRIES OF CURRENT ROW ARE FILLED 
        '3  IF FILLED THEN SAVE IT IN WSALEDET(SAVE TEMPORARY
        '4  ELSE FIRE MSG FOR BLANK COLUMN
        If BtLoading = 0 Then Exit Sub
        Try
            '1.
            If e.NewRange.r1 <> e.NewRange.r2 Then Exit Sub 'Exit at multiple Selection
            If e.NewRange.r1 = e.OldRange.r1 Then Exit Sub
            If IsNothing(fgItems.Item(e.OldRange.r1, "ITEMID")) OrElse Trim(fgItems.Item(e.OldRange.r1, "ITEMID").ToString()) = "" Then 'Check added for return true if item is not selected 
                If e.NewRange.r1 > e.OldRange.r1 Then e.Cancel = True
                Exit Sub  'THERE IS NOT ITEM ENTERED EXIT SUB
            Else '2
                Dim intBlankColumn As Integer = ItemDetailsFilled(e.OldRange.r1) '2
                If intBlankColumn = 0 Then
                    If btStatus = 1 OrElse (fgItems.Item(e.OldRange.r1, "STATUS") <> "W" AndAlso fgItems.Item(e.OldRange.r1, "STATUS") <> "F") Then 'CHANGES ARE DONE NEED TO SAVE.
                        If SaveCurrentItem(e.OldRange.r1) < 1 Then e.Cancel = True '3
                    Else : Exit Sub 'NO CHANGES ARE DONE 
                    End If
                Else : e.Cancel = True '4
                End If
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "fgItems_BeforeRowColChange")
        End Try
    End Sub

    Private Sub fgItems_BeforeMouseDown(ByVal sender As Object, ByVal e As C1.Win.C1FlexGrid.BeforeMouseDownEventArgs) Handles fgItems.BeforeMouseDown
        Try
            With fgItems
                If IsNothing(.Item(.Row, "ITEMID")) OrElse Trim(.Item(.Row, "ITEMID").ToString()) = "" Then 'Check added for return true if item is not selected 
                    If .MouseRow > intCurrentRow Then e.Cancel = True
                    Exit Sub  'THERE IS NOT ITEM ENTERED EXIT SUB
                End If
            End With
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "fgItems_BeforeMouseDown")
        End Try
    End Sub
#End Region '"GRID EVENT FUNCTIONS"

#Region "USER DEFINED FUNCITONS"

    Private Sub showProductList(ByVal intColumnIndex As Integer, Optional ByVal keyChar As Char = "")
        Dim intSelectedProduct As Integer
        Dim btContinue As Byte = 0
        Try
            With fgItems
                If IsNothing(.Item(.Row, "STATUS")) Then
                    If .Row = 0 Then
                        Exit Sub
                    ElseIf .Row = 1 Then
                        btContinue = 1
                    ElseIf Not IsNothing(.Item(.Row - 1, "ITEMID")) OrElse Trim(.Item(.Row - 1, "ITEMID")) <> "" Then
                        btContinue = 1
                    End If
                ElseIf .Item(.Row, "STATUS") = "" OrElse .Item(.Row, "STATUS") = "A" Then 'ITEM SHOULD BE UPDATE ONLY IF ITEM IS ACTIVE NOT FOR :-.ITEM(.ROW, "STATUS") = "U" ORELSE .ITEM(.ROW, "STATUS") = "W" 
                    btContinue = 1
                End If
                If btContinue = 0 Then Exit Sub
            End With
            Dim frmListProducts As New frmProducts
            'CHECK CURRENT ROW IS NOT AFTER BLANK ROW IF IT IS THEN EXIT SUB
            With fgItems
                frmListProducts.Left = .Cols("CLRcode").Left + .Left + Me.Left + 5
                frmListProducts.Top = .Rows(0).Bottom + fgItems.Top + Me.Top
                frmListProducts.Height = .Height - .Rows.DefaultSize - 2
                frmListProducts.Width = .Width - .Cols("CODE").Width - .Cols("ITEMNAME").Width - .Cols("COMPANY").Width - 15
                'frmListProducts.intColumnIndex = IIf(intColumnIndex > 2, 2, intColumnIndex)
                '                frmListProducts.keyChar = keyChar
                If .Item(.Row, intColumnIndex) <> Nothing Then
                    If Not IsNothing(.Item(.Row, "ITEMID")) AndAlso Trim(.Item(.Row, "ITEMID")) Then frmProducts.intSelectedItem = .Item(.Row, "ITEMID")
                End If
                frmListProducts.ShowDialog()
                intSelectedProduct = frmListProducts.intSelectedItem
            End With



            '' '' '' '' '' '' '' ''CHECK CURRENT ROW IS NOT AFTER BLANK ROW IF IT IS THEN EXIT SUB
            ' '' '' '' '' '' '' ''With fgItems
            ' '' '' '' '' '' '' ''    frmListProducts.Left = .Cols("CLRcode").Left + .Left + Me.Left + 5
            ' '' '' '' '' '' '' ''    frmListProducts.Top = .Rows(0).Bottom + fgItems.Top + Me.Top
            ' '' '' '' '' '' '' ''    frmListProducts.Height = .Height - .Rows.DefaultSize - 2
            ' '' '' '' '' '' '' ''    frmListProducts.Width = .Width - .Cols("CODE").Width - .Cols("ITEMNAME").Width - .Cols("COMPANY").Width - 15
            ' '' '' '' '' '' '' ''    frmListProducts.intColumnIndex = IIf(intColumnIndex > 2, 2, intColumnIndex)
            ' '' '' '' '' '' '' ''    frmProducts.intSelectedItem = 0
            ' '' '' '' '' '' '' ''    frmListProducts.keyChar = keyChar
            ' '' '' '' '' '' '' ''    If .Item(.Row, intColumnIndex) <> Nothing Then
            ' '' '' '' '' '' '' ''        If Not IsNothing(.Item(.Row, "ITEMID")) AndAlso Trim(.Item(.Row, "ITEMID")) Then frmProducts.intSelectedItem = .Item(.Row, "ITEMID")
            ' '' '' '' '' '' '' ''    End If
            ' '' '' '' '' '' '' ''    frmListProducts.ShowDialog()
            ' '' '' '' '' '' '' ''    intSelectedProduct = frmListProducts.intSelectedItem
            ' '' '' '' '' '' '' ''End With

            If intSelectedProduct > 0 Then
                btStatus = 0
                BtLoading = 0
                With frmListProducts.fgProducts
                    If .CurrentRow.Index > 0 Then
                        intCurrentRow = fgItems.Row
                        If fgItems.Item(fgItems.Row, "ITEMID") <> .Item("ITEMID", .CurrentRow.Index).ToString Then Call ShowItemInfo(.Item("ITEMID", .CurrentRow.Index).Value)
                        fgItems.Item(fgItems.Row, "ITEMID") = .Item(.CurrentRow.Index, 0)
                        fgItems.Item(fgItems.Row, "CODE") = .Item(.CurrentRow.Index, 1)
                        fgItems.Item(fgItems.Row, "NAME") = .Item(.CurrentRow.Index, 2)
                        fgItems.Item(fgItems.Row, "LOCATION") = .Item(.CurrentRow.Index, 5)
                        fgItems.Item(fgItems.Row, "COMPANY") = .Item(.CurrentRow.Index, 3)
                        'fgItems.Item(fgItems.Row, "CLRcode") = ""
                        'fgItems.Item(fgItems.Row, "QTY") = "1"
                        'fgItems.Item(fgItems.Row, "RATE") = "0.00"
                        'fgItems.Item(fgItems.Row, "AMOUNT") = "0.00"
                        'fgItems.Item(fgItems.Row, "STATUS") = "A"

                        'SELECT warnMessage FROM mWarning WHERE WarnModule='SALE' AND warnBase='SCHEDULE' AND warnValue='X'
                        If Trim(.Item(7, .CurrentRow.Index).Value) <> "" Then
                            Dim strWarning As String = DItem.GetWarningMessage("SALE", "SCHEDULE", Trim(.Item(7, .CurrentRow.Index).Value))
                            If strWarning <> "" Then
                                DisplayShedule(strWarning, .Item(7, .CurrentRow.Index).Value) 'SCHEDULE TYPE
                            Else
                                DisplayShedule("", "")
                            End If
                        End If
                        fgItems.Item(fgItems.RowSel, "EMERGENCYSTOCK") = .Item(.CurrentRow.Index, 8) 'EMERGENCY STOCK
                        fgItems.Item(fgItems.RowSel, "TOTALSTOCK") = .Item(.CurrentRow.Index, 4) 'TOTAL STOCK
                        intCurrentRow = fgItems.Row
                        BtLoading = 1
                        If fgItems.Col = fgItems.Cols("CLRcode").Index Then
                            Call fgItems_EnterCell(Nothing, Nothing)
                        Else
                            fgItems.Col = fgItems.Cols("CLRcode").Index    'Batch  'After item Selection show Batch Selection
                        End If
                        Call CalculateAmt()
                    End If
                End With
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "showProductList")
        End Try
    End Sub

    ''Private Sub SetActiveCell(ByVal intRow As Integer, ByVal intCol As Integer)
    ''    Try
    ''        With fgItems
    ''            .Row = intRow
    ''            .RowSel = intRow
    ''            .Col = intCol
    ''            .ColSel = intCol
    ''        End With
    ''    Catch ex As Exception
    ''        BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "SetActiveCell")
    ''    End Try
    ''End Sub

    Private Sub DisplayShedule(ByVal strWarning As String, ByVal Schedule As String)
        Try
            If strWarning <> "" Then  'SHOW
                lblInfo12.Visible = True
                lblInfo12.BringToFront()
                lblInfo12.Text = strWarning
                'lblInfo12.Text = UCase(strWarning)
                fgItems.Item(fgItems.RowSel, "SCHEDULEDRUG") = Schedule 'SCHEDULE TYPE
            Else
                lblInfo12.Visible = False
                lblInfo12.SendToBack()
                lblInfo12.Text = ""
                fgItems.Item(fgItems.RowSel, "SCHEDULEDRUG") = "" 'SCHEDULE TYPE
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "DisplayShedule")
        End Try
    End Sub

    Private Sub showBatchDetails()
        Try
            With fgBatch

                .Left = fgItems.Cols("CLRcode").Left + fgItems.Left - 3
                .Top = .Rows(0).Bottom '+ fgItems.Top + Me.Top
                .DataSource = DStock.GetStockBatchs(fgItems.Item(fgItems.RowSel, "ITEMID"))
                '0:BATCH,1:EXPIRY,2:STOCK,3:SALEPRICE,4:CONVERSIONFACTOR,5:PURCHASEPRICE ,6:SCHEMEID,7:SCHEMEITEMQTY
                .Cols("CONVERSIONFACTOR").Visible = False
                .Cols("SCHEMEID").Visible = False
                .Cols("SCHEMEITEMQTY").Visible = False
                .Cols("MRP").Visible = False

                .Cols("BATCH").Width = (.Width - 3) * (25 / 100)
                .Cols("EXPIRY").Width = (.Width - 3) * (17.5 / 100)
                .Cols("STOCK").Width = (.Width - 3) * (17.5 / 100)
                .Cols("SALEPRICE").Width = (.Width - 3) * (17.5 / 100)
                .Cols("PURCHASEPRICE").Width = (.Width - 3) * (22.5 / 100)
                .Cols("MRP").Width = 0

                If fgItems.Item(fgItems.RowSel, "CLRcode") <> "" Then
                    Dim intRow As Integer = .FindRow(fgItems.Item(fgItems.RowSel, "CLRcode"), 1, 0, False)  '
                    If intRow > 0 Then .RowSel = intRow : .Row = intRow
                ElseIf .Rows.Count = 2 Then  'IF THERE IS ONLY ONE BATCH IT SHOULD BE AUTOMATIC SELECTED
                    .RowSel = 1
                    .Row = 1
                    fgItems.Item(fgItems.Row, "ISMULTIBATCH") = 0 '"ISMULTIBATCH" 
                    Call SelectBatch()
                    Exit Sub
                ElseIf .Rows.Count > 2 Then
                    .RowSel = 1
                    .Row = 1
                    'ITEM HAS MULTIPLE BATCH STOCK
                    fgItems.Item(fgItems.Row, "ISMULTIBATCH") = 1 '"ISMULTIBATCH"
                Else
                    .RowSel = -1
                    .Row = -1
                End If
                .Visible = True
                .Focus()
            End With

        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "showBatchDetails")
        End Try

    End Sub


    Private Sub DisplayData()
        Try

            BtLoading = 0
            intCurrentRow = 1
            'Me.StartPosition = FormStartPosition.Manual

            txtVoucher.Text = BCommon.GetSequentialID("SALEPRINT")

            'BCommon.SetComboValues(cmDDoctor, DDoctor.GetDoctorList(), "DoctorID", "Name")
            BCommon.SetComboValues(cmDCustomerName, DCustomer.GetCustomerName(), "CustID", "Name")
            BCommon.SetComboValues(cmbTitle, "TITLE", False)
            BCommon.SetTextReadOnly(txtVoucher) 'Divya 31/01/2008 : Added for ReadOnly fields
            BCommon.SetTextReadOnly(txtTotal)
            BCommon.SetTextReadOnly(txtNetAmount)
            BCommon.SetTextReadOnly(txtBalance)

            Call SetGrids()
            Call SetColumnWidths()

            fgBatch.Parent = fgItems
            pnlShortCuts.Location = fgItems.Location
            pnlShortCuts.Size = fgItems.Size

            'Set Values
            Dim dtCity As DataTable = DAddress.GetCity()
            For Each drCity As DataRow In dtCity.Select("CityCD=" & BCommon.GetConfigValues("City"))
                txtAddress.Text = drCity("Description").ToString
            Next


            'FROM FRMSALE-DISPLAYDATA

            dtpSaleDate.Value = Now.Date
            dtpSaleDate.Enabled = False


            If intSaleType <> 3 Then
                Call LoadData()
                Call CalculteTotalAmt()
                Call CalculateProfitAmt()
            Else
                PrintBill = 1
            End If
            'Call LoadData()
            'Call CalculteTotalAmt()
            If PrintBill = 1 Then
                Me.chkPrintReport.Checked = True
            Else
                Me.chkPrintReport.Checked = False
            End If
            BtLoading = 1
            Me.FormBorderStyle = Windows.Forms.FormBorderStyle.None
            lblInfo12.ForeColor = Color.Red
            strExistingItems = GetDeletedItems()
            rTxtShortCuts.LoadFile(System.AppDomain.CurrentDomain.BaseDirectory() & "\REGShortCuts.rtf")

        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "DisplayData")
        End Try
    End Sub

    Private Sub LoadData()
        Try
            With fgItems
                Dim intCount As Integer
                Dim intColCount As Integer
                If .Rows.Count <= ItemsFromSale.Count + 1 Then .Rows.Count = ItemsFromSale.Count + 10


                For intCount = 1 To ItemsFromSale.Count
                    For intColCount = 0 To .Cols.Count - 1
                        .Item(intCount, intColCount) = ItemsFromSale.Item(intCount - 1).Item(intColCount)
                    Next
                    If .Item(intCount, "STATUS") = "F" Then
                        .Rows(intCount).AllowEditing = False
                        SetRowColor(intCount, "F")
                    Else
                        SetRowColor(intCount, "T")
                    End If

                Next
                .Row = intCount - 1
                .Refresh()
                btStatus = 1
            End With
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "LoadData")
        End Try
    End Sub

    ''Private Sub ClearData()
    ''    Try
    ''        intDelete = 0
    ''        BtLoading = 0
    ''        btMltplMRP = 0
    ''        intCurrentRow = 1
    ''        intCurrentCol = 1
    ''        btStatus = 1
    ''        TotAmount = 0.0
    ''        txtBalance.Text = "0.00"
    ''        txtNetAmount.Text = "0.00"
    ''        txtPaidAmt.Text = "0.00"
    ''        txtDiscount.Text = "0.00"
    ''        txtDisPercent.Text = "0.00"
    ''        txtProfit.Text = "0.00"
    ''        lblInfo12.Visible = False
    ''        lblInfo12.Text = ""
    ''        lblInfo12.SendToBack()
    ''        pnlShortCuts.Visible = False
    ''        Call ClearItemInfo()
    ''        Call DisplayShedule("", "")
    ''        With fgItems
    ''            .Rows.Count = 30
    ''            .Clear(C1.Win.C1FlexGrid.ClearFlags.Content, 1, 0, .Rows.Count - 1, .Cols.Count - 1)
    ''            .Clear(C1.Win.C1FlexGrid.ClearFlags.Style, 1, 1, .Rows.Count - 1, 1)
    ''            .Styles.Alternate.BackColor = Color.White ' Me.BackColor 'Color.AliceBlue  '
    ''            .Styles.Normal.TextEffect = C1.Win.C1FlexGrid.TextEffectEnum.Raised
    ''            .Styles.EmptyArea.BackColor = Color.White  ' Me.BackColor  'Color.AliceBlue 'Me.BackColor
    ''            .Styles.Normal.BackColor = Color.White   'Me.BackColor  'Color.AliceBlue 'Me.BackColor
    ''            .Styles.Alternate.TextEffect = C1.Win.C1FlexGrid.TextEffectEnum.Raised
    ''            .AllowEditing = True
    ''        End With
    ''        BtLoading = 1
    ''    Catch ex As Exception
    ''        BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "ClearData")
    ''    End Try
    ''End Sub

    Private Function SaveData(ByVal IsFinalBill As Boolean) As Integer
        Dim custID As Integer
        Try
            If ValidateData() Then
                If IsFinalBill AndAlso CDbl(IIf(txtPaidAmt.Text <> "", txtPaidAmt.Text, 0)) < CDbl(IIf(txtNetAmount.Text <> "", txtNetAmount.Text, 0)) Then
                    BCommon.ShowMsgError(10086)
                    txtPaidAmt.Text = txtNetAmount.Text
                    txtBalance.Text = "0.00"
                    Return False
                End If
                If cmDCustomerName.SelectedValue <> Nothing Then
                    custID = cmDCustomerName.SelectedValue
                ElseIf Trim(cmDCustomerName.Text) = "" Then
                    BCommon.ShowMsgError(10309)
                    cmDCustomerName.Focus()
                    Return 0
                ElseIf Trim(cmDCustomerName.Text <> "") Then
                    Dim Person As CPerson = SetData()
                    custID = DCustomer.SaveCust(Person, "C", DoctorID, 0, intCityCD)
                End If
            Else : Return 0
            End If

            Dim objsale As CSale
            Dim objsaleItem() As cSaleItem = Nothing

            Dim intResult As Integer

            If Not IsNothing(fgItems.Item(fgItems.Row, "STATUS")) AndAlso (Trim(fgItems.Item(fgItems.Row, "STATUS")) = "A" OrElse Trim(fgItems.Item(fgItems.Row, "STATUS")) = "U") Then
                SaveCurrentItem(fgItems.Row)
            End If

            objsale = SetSaleData(custID)
            objsale.IsFinalBill = IsFinalBill
            objsaleItem = SetSaleItemDetails()
            intResult = DSale.Save(objsale, objsaleItem)
            If intResult > 0 Then

                IsBillSaved = 1
                If BCommon.ShowMsgError(10321, "YN") = Windows.Forms.DialogResult.Yes Then
                    Call PrintFinalBIll()
                    'frmPrintBill.SaleID = intResult
                    'frmPrintBill.Show()
                End If
                Me.Close()
                Return intResult
            Else
                IsBillSaved = 0
                BCommon.ShowMsgError(4)
                Return 0
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "SaveData")
            Return 0
        End Try
    End Function
    Private Sub SetItemAmount(ByVal intRow As Integer)
        Try

            With fgItems
                Dim FinalAmount As Double = CDbl(.Item(intRow, "QTY")) * CDbl(.Item(intRow, "RATE"))

                If Not IsNothing(.Item(intRow, "SCHEMEID")) Then

                    Dim Scheme As CScheme = CType(.Item(intRow, "SCHEMEID"), CScheme)

                    If Scheme.DiscountType = "A" Then
                        Scheme.DiscountAmount = CDbl(.Item(intRow, "QTY")) * (Scheme.Discount / .Item(intRow, "CONVERSIONUNIT"))

                    ElseIf Scheme.DiscountType = "P" Then
                        Scheme.DiscountAmount = BCALC.GetDiscountAmount(FinalAmount, Scheme.Discount) / .Item(intRow, "CONVERSIONUNIT")
                    End If
                    FinalAmount -= Scheme.DiscountAmount

                    .Item(intRow, "SCHEMEID") = Scheme
                End If

                .Item(intRow, "AMOUNT") = Math.Round(FinalAmount, 2)
            End With

        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "SetItemAmount")
        End Try
    End Sub

    Private Sub SelectBatch()
        If btInSelectBatch = 1 Then Exit Sub
        Try
            With fgBatch
                If .RowSel < 1 Then Exit Sub
                btInSelectBatch = 1
                '0:BATCH,1:EXPIRY,2:STOCK,3:SALEPRICE,4:CONVERSIONFACTOR,5:PURCHASEPRICE ,6:SCHEMEID,7:SCHEMEITEMQTY
                btStatus = 0
                fgItems.Item(fgItems.RowSel, "CLRcode") = .Item(.RowSel, "BATCH")
                fgItems.Item(fgItems.RowSel, "EXPIRY") = .Item(.RowSel, "EXPIRY")
                fgItems.Item(fgItems.RowSel, "BATCHQTY") = .Item(.RowSel, "STOCK")

                fgItems.Item(fgItems.RowSel, "RATE") = CDbl(.Item(.RowSel, "SALEPRICE") / .Item(.RowSel, "CONVERSIONFACTOR"))

                fgItems.Item(fgItems.RowSel, "CONVERSIONUNIT") = .Item(.RowSel, "CONVERSIONFACTOR")
                fgItems.Item(fgItems.RowSel, "PURCHASEPRICE") = CDbl(.Item(.RowSel, "PURCHASEPRICE") / .Item(.RowSel, "CONVERSIONFACTOR"))
                Dim defalultScheme As New CScheme
                If .Item(.RowSel, "SCHEMEID") > 0 Then  'IF SCHEME IS PRESENT TO THIS ITEM
                    Dim ItemScheme As CScheme = BScheme.GetScheme(.Item(.RowSel, "SCHEMEID"))
                    If Not IsNothing(ItemScheme) Then
                        fgItems.Item(fgItems.RowSel, "SCHEMEID") = ItemScheme
                        fgItems.Item(fgItems.RowSel, "SCHEMESTOCK") = .Item(.RowSel, "SCHEMEITEMQTY")
                        fgItems.Item(fgItems.RowSel, "SCHEME") = ItemScheme.GetSchemeName
                    Else
                        fgItems.Item(fgItems.RowSel, "SCHEMEID") = defalultScheme
                        fgItems.Item(fgItems.RowSel, "SCHEMESTOCK") = 0
                    End If
                Else
                    fgItems.Item(fgItems.RowSel, "SCHEMEID") = defalultScheme
                    fgItems.Item(fgItems.RowSel, "SCHEMESTOCK") = 0
                End If
                .Visible = False

                'SET TAX IF IT IS

                If BCommon.GetConfigValues("TAX") = 1 Then 'TAX IS APPLICABLE
                    fgItems.Item(fgItems.RowSel, "TAX") = Math.Round((fgItems.Item(fgItems.RowSel, "RATE") * BTax.GetSaleTaxValue(fgItems.Item(fgItems.RowSel, "ITEMID"), .Item(.RowSel, "BATCH")) / 100), 2)
                    fgItems.Item(fgItems.RowSel, "RATE") += fgItems.Item(fgItems.RowSel, "TAX")
                    fgItems.Item(fgItems.RowSel, "MAXRATE") = CDbl(.Item(.RowSel, "MRP") / .Item(.RowSel, "CONVERSIONFACTOR")) + fgItems.Item(fgItems.RowSel, "TAX")
                Else 'TAX IS NOT APPLICABLE
                    fgItems.Item(fgItems.RowSel, "TAX") = 0
                    fgItems.Item(fgItems.RowSel, "MAXRATE") = CDbl(fgItems.Item(fgItems.RowSel, "MRP") / .Item(.RowSel, "CONVERSIONFACTOR"))
                End If

                Call ShowItemInfo(fgItems.Item(fgItems.RowSel, "ITEMID"), .Item(.RowSel, 0))
                fgItems.Focus()
                fgItems.Col = fgItems.Cols("QTY").Index
                Call CalculateAmt()
                Call CalculteTotalAmt()
                Call CalculateProfitAmt()
                btInSelectBatch = 0
            End With

        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "SelectBatch")
        End Try
    End Sub

    Private Function ItemDetailsFilled(ByVal intItemRow As Integer) As Integer
        Try
            With fgItems.Rows(intItemRow)
                If .Item("CLRcode") = Nothing OrElse Trim(.Item("CLRcode").ToString()) = "" Then Return 7
                If .Item("QTY") = Nothing OrElse Trim(.Item("QTY").ToString()) = "" Then Return 8
                If .Item("RATE") = Nothing OrElse Trim(.Item("RATE").ToString()) = "" Then Return 9
            End With
            Return 0
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "ItemDetailsFilled")
        End Try

    End Function

    Private Function SetSaleData(ByVal CustID As Integer) As CSale
        Dim objsale As New CSale
        Dim intCount As Integer
        TotAmount = 0.0
        Try
            With objsale
                .PartyID = CustID
                .PromoterID = intCounter
                .SaleDate = Me.dtpSaleDate.Value
                For intCount = 1 To fgItems.Rows.Count
                    If CDbl(fgItems.Cols("AMOUNT").Item(intCount)) = 0.0 Then Exit For
                    TotAmount = TotAmount + fgItems.Cols("AMOUNT").Item(intCount)
                Next
                .Amount = TotAmount
                '.Amount = checkTextBox(txtTotal.Text)
                .Discount = checkTextBox(txtDiscount.Text)
                .PaidAmt = checkTextBox(txtPaidAmt.Text)
                .TotalTax = checkTextBox(txtTax.Text)
                .DebitAmt = checkTextBox(txtDebit.Text)
                .CreditAmt = checkTextBox(txtCredit.Text)
                .GrossAmt = txtNetAmount.Text
                If Convert.ToDouble(Me.txtNetAmount.Text) > Convert.ToDouble(Me.txtPaidAmt.Text) Then
                    .SaleType = "CS"
                ElseIf Convert.ToDouble(Me.txtNetAmount.Text) = Convert.ToDouble(Me.txtPaidAmt.Text) Then
                    .SaleType = "CR"
                End If
                .DrID = DoctorID
            End With
            Return objsale
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "SetSaleData")
            Return Nothing
        End Try
    End Function

    Private Function SetSaleItemDetails() As cSaleItem()
        Dim objsaleItem() As cSaleItem
        Dim intCount As Integer
        Dim intRowCount As Integer = 0
        Try
            For intCount = 1 To fgItems.Rows.Count - 1
                If fgItems.Item(intCount, "ITEMID") = Nothing OrElse Trim(fgItems.Item(intCount, "ITEMID")) = "" Then
                    Exit For
                Else : intRowCount = intRowCount + 1
                End If
            Next
            ReDim objsaleItem(intRowCount - 1)
            For intCount = 0 To intRowCount - 1
                objsaleItem(intCount) = New cSaleItem
                objsaleItem(intCount) = SetSaleItemDetail(intCount + 1, fgItems.Cols("STATUS").Item(intCount + 1))
            Next
            Return objsaleItem
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "SetSaleItemDetails")
            Return Nothing
        End Try
    End Function

    Private Function SetSaleItemDetail(ByVal intRow As Integer, ByVal chrSaveOrUpdate As Char) As cSaleItem
        Dim Item As cSaleItem = New cSaleItem
        Try

            With Item
                .CLRcode = Trim(fgItems.Cols("CLRcode").Item(intRow))
                .Counter = intCounter
                .ItemID = fgItems.Cols("ITEMID").Item(intRow)
                .Quantity = fgItems.Cols("QTY").Item(intRow)
                .Amount = fgItems.Cols("AMOUNT").Item(intRow)
                .SaleRate = fgItems.Cols("RATE").Item(intRow)
                'Kiran@ITS on  03/14/2008:
                '.ExpiryDate = fgItems.Cols("EXPIRY").Item(intRow)
                .ExpiryDate = BCommon.GetDatewithLastDay(fgItems.Cols("EXPIRY").Item(intRow))
                .Status = chrSaveOrUpdate
                .CounterSeqID = fgItems.Cols("SEQID").Item(intRow)
                '                .ItemsPerPack = IIf(Trim(fgItems.Cols("CONVERSIONUNIT").Item(intRow)) = "", 0, fgItems.Cols("CONVERSIONUNIT").Item(intRow))
                If IsNothing(fgItems.Cols("SCHEMEID").Item(intRow)) Then
                    .SchemeID = 0
                Else
                    .SchemeID = CType(fgItems.Cols("SCHEMEID").Item(intRow), CScheme).SchemeID
                End If
                If Trim(fgItems.Cols("SCHEMESTOCK").Item(intRow)) <> "" AndAlso fgItems.Cols("SCHEMESTOCK").Item(intRow) > 0 AndAlso Trim(fgItems.Cols("SCHEME").Item(intRow)) <> "" Then
                    .SchemeQuantity = fgItems.Cols("SCHEME").Item(intRow)
                Else
                    .SchemeQuantity = 0
                End If

                .SchemeDiscount = IIf(.SchemeID > 0 AndAlso Trim(fgItems.Cols("SCHEMESTOCK").Item(intRow)) <> "" AndAlso fgItems.Cols("SCHEMESTOCK").Item(intRow) = 0, CType(fgItems.Cols("SCHEMEID").Item(intRow), CScheme).DiscountAmount, 0)


                If IsNothing(fgItems.Cols("STOCKDETAILS").Item(intRow)) Then
                    .StockDetails = ""
                Else : .StockDetails = fgItems.Cols("STOCKDETAILS").Item(intRow)
                End If
                .FreeReplacement = "F"
            End With

            Return Item
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "SetSaleItemDetail")
            Return Nothing
        End Try
    End Function


    Private Sub SetRowColor(ByVal RowNo As Integer, ByVal ColorFor As Char)
        Try
            With fgItems
                Dim FreezeStyle As C1.Win.C1FlexGrid.CellStyle
                FreezeStyle = .Rows(RowNo).StyleNew
                Select Case ColorFor
                    Case "F"   'Freezed, SAVED,
                        FreezeStyle.BackColor = CConstants.FreezedRowColor
                    Case "T"   'SAVED IN WORKING
                        FreezeStyle.BackColor = CConstants.ActiveRowColor
                    Case "A"   'ACTIVE
                        FreezeStyle.BackColor = CConstants.CurentRowColor
                    Case Else  'NORMAL
                        FreezeStyle.BackColor = .Rows(.Cols.Count - 1).Style.BackColor
                End Select
                .Rows(RowNo).Style = FreezeStyle
            End With
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "SetRowColor")
        End Try
    End Sub

    Private Sub SetRowColor(ByRef Row As C1.Win.C1FlexGrid.Row, ByVal ColorFor As Char)
        Try
            Dim FreezeStyle As C1.Win.C1FlexGrid.CellStyle
            FreezeStyle = Row.StyleNew
            Select Case ColorFor
                Case "F"   'Freezed, SAVED,
                    FreezeStyle.BackColor = CConstants.FreezedRowColor
                Case "T"   'SAVED IN WORKING
                    FreezeStyle.BackColor = CConstants.CurentRowColor
                Case "A"   'ACTIVE
                    FreezeStyle.BackColor = CConstants.ActiveRowColor
                Case Else  'NORMAL
                    FreezeStyle.BackColor = fgItems.Rows(fgItems.Cols.Count - 1).Style.BackColor
            End Select
            Row.Style = FreezeStyle
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "SetRowColor")
        End Try
    End Sub

    ''Private Function ValidateAmt() As Boolean
    ''    Dim intPaidAmt As Double = 0
    ''    Dim intGrossAmt As Double = 0
    ''    Dim intcount As Integer = 0
    ''    Try
    ''        With fgItems
    ''            If .Rows.Count > 0 Then
    ''                If IsNothing(.Item(1, "ITEMID")) Then
    ''                    BCommon.ShowMsgError(10234)
    ''                    .Col = .Cols("ITEMNAME").Index
    ''                    Return False
    ''                End If
    ''                For intcount = 0 To .Rows.Count - 1
    ''                    If IsNothing(.Item(intcount, "ITEMID")) = False OrElse .Item(intcount, "ITEMID") <> "" Then
    ''                        If IsNothing(.Item(intcount, "CODE")) Or .Item(intcount, "CODE") = "" Then  'Validate Item Name
    ''                            BCommon.ShowMsgError(10235)
    ''                            Return False
    ''                        ElseIf IsNothing(.Item(intcount, "CLRcode")) Or .Item(intcount, "CLRcode") = "" Then  'Validate Batch No.
    ''                            BCommon.ShowMsgError(10236)
    ''                            Return False
    ''                        End If
    ''                    End If
    ''                Next
    ''            End If
    ''        End With

    ''        'VALIDATE AMOUNT
    ''        If Me.txtPaidAmt.Text <> "" Then
    ''            intPaidAmt = Convert.ToDouble(Me.txtPaidAmt.Text.ToString())
    ''        End If
    ''        If Me.txtTotal.Text <> "" Then
    ''            intGrossAmt = Convert.ToDouble(Me.txtTotal.Text.ToString())
    ''        End If
    ''        If intPaidAmt < intGrossAmt Then
    ''            BCommon.ShowMsgError(10171)
    ''            Me.txtPaidAmt.Focus()
    ''            Return False
    ''        Else
    ''            Me.txtBalance.Text = Format((intPaidAmt - intGrossAmt), "0.00")
    ''            Return True
    ''        End If
    ''        Return True
    ''    Catch ex As Exception
    ''        BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "ValidateAmt")
    ''    End Try
    ''End Function

    Private Function ValidateInfo() As Boolean
        Dim intcount As Integer = 0
        Try
            With fgItems
                If DateTime.Compare(dtpSaleDate.Value, DateTime.Now()) > 0 Then
                    BCommon.ShowMsgError(10238)
                    dtpSaleDate.Value = DateTime.Now()
                    dtpSaleDate.Focus()
                    Return False
                ElseIf .Rows.Count > 0 Then
                    If IsNothing(.Item(1, "ITEMID")) Then
                        BCommon.ShowMsgError(10234)
                        .Col = .Cols("ITEMNAME").Index
                        Return False
                    End If
                    ''Dim btSchedule As Byte = 0
                    For intcount = 1 To .Rows.Count - 1
                        If IsNothing(.Item(intcount, "ITEMID")) = False OrElse Trim(.Item(intcount, "ITEMID")) <> "" Then
                            If IsNothing(.Item(intcount, "CODE")) Or .Item(intcount, "CODE") = "" Then  'VALIDATE FOR ITEM NAME.
                                BCommon.ShowMsgError(10235)
                                Return False
                            End If
                            If IsNothing(.Item(intcount, "CLRcode")) Or .Item(intcount, "CLRcode") = "" Then  'VALIDATE BATCH NO.
                                BCommon.ShowMsgError(10236)
                                .Col = .Cols("CLRcode").Index
                                showBatchDetails()
                                Return False
                            End If
                            'CHECK FOR SCHEDULE ITEM. IF ANY ITEM IS SCHEDULE THEN IT CAN NOT BE SAVED IN COUNTER SALE SO RETURN FALSE
                            'If btSchedule = 0 Then
                            '    If .Item(intcount, "SCHEDULEDRUG") <> "" Then
                            '        If MessageBox.Show(BCommon.GetMessage(10253), BCommon.GetConfigValues("MsgTitle"), MessageBoxButtons.YesNo) = Windows.Forms.DialogResult.Yes Then
                            '            btSchedule = 1
                            '        Else
                            '            .Row = intcount
                            '            lblSchedule.Text = DItem.GetWarningMessage("SALE", "SCHEDULE", Trim(.Item(intcount, "SCHEDULEDRUG")))
                            '            lblSchedule.Visible = True
                            '            Return False
                            '        End If
                            '    End If
                            'End If
                        Else : Exit For
                        End If
                    Next
                End If
            End With
            Return True
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "ValidateInfo")
        End Try
    End Function

    Private Function GetSchemeQty(ByVal SchemeRow As Integer, ByVal SchemeOnQty As Integer) As Integer
        'RETURNS SCHEME APPLICABLE SCHEME QUANTITY .
        Try
            Dim Scheme As CScheme = fgItems.Item(SchemeRow, "SCHEMEID")
            Return BScheme.GetSchemeQty(Scheme.SchemeID, SchemeOnQty)
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "GetSchemeQty")
            Return 0
        End Try
    End Function

    Private Sub DisplayShortCuts(ByVal ShowOrHide As Char)
        Try
            If ShowOrHide = "S" Then  'Show ShortCuts
                pnlShortCuts.BringToFront()
                pnlShortCuts.Visible = True
                grpCalculation.Enabled = False
                fgItems.Visible = False
            ElseIf ShowOrHide = "H" Then 'Show Regular Sale 'hide others
                fgItems.Visible = True
                fgItems.BringToFront()
                pnlShortCuts.Visible = False
                grpCalculation.Enabled = True

            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "DisplayShortCuts")
        End Try
    End Sub

    Private Function SaveCurrentItem(ByVal intCurrentItem As Integer) As Byte
        Try
            Dim chrSaveOrUpdate As Char
            With fgItems
                '--------------------------------------------------------
                If .Item(intCurrentItem, "STATUS") = Nothing Or .Item(intCurrentItem, "STATUS") = "A" Then
                    chrSaveOrUpdate = "W"
                ElseIf .Item(intCurrentItem, "STATUS") = "W" Then
                    chrSaveOrUpdate = "U"
                ElseIf .Item(intCurrentItem, "STATUS") = "U" Then
                    chrSaveOrUpdate = "U"
                Else : Exit Function
                End If
                '--------------------------------------------------------
                Dim ItemToSave As cSaleItem = SetSaleItemDetail(intCurrentItem, chrSaveOrUpdate)
                If DSale.SaveSaleItem(ItemToSave, chrSaveOrUpdate) > 0 Then

                    .Item(intCurrentItem, "STATUS") = "W" 'chrSaveOrUpdate 'AFTER SAVING CURRENT ITEM ITS TREATED AS SAVED IN WORKING TABLE(NO MATTERS UPDATED OR DIRECT)
                    .Item(intCurrentItem, "SEQID") = ItemToSave.CounterSeqID
                    .Item(intCurrentItem, "STOCKDETAILS") = ItemToSave.StockDetails ' Stock Details
                    btStatus = 1
                    SetRowColor(intCurrentItem, "T")
                    intCurrentItem = .Row
                    If lblInfo12.Visible = True Then
                        lblInfo12.Visible = False
                        lblInfo12.Text = ""
                    End If
                    Call ClearItemInfo() 'CLEARITEM INFORMATION
                    Return 1
                Else : Return 0
                End If
            End With
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "SaveCurrentItem")
        End Try
    End Function


    Private Sub ShowItemInfo(ByVal ItemID As Integer, Optional ByVal CLRcode As String = "")
        Try
            Call ClearItemInfo()
            Dim dtDItem As New DataTable
            dtDItem = IIf(CLRcode = "", DItem.GetItemInfo(ItemID), DItem.GetItemInfo(ItemID, CLRcode))

            If dtDItem.Rows.Count > 0 Then
                With dtDItem.Rows(0)
                    For intCount As Integer = 0 To dtDItem.Columns.Count - 1
                        Select Case intCount
                            Case 0
                                lblInfo1.Text = dtDItem.Columns(intCount).Caption & " : " & .Item(intCount)
                            Case 1
                                lblInfo2.Text = dtDItem.Columns(intCount).Caption & " : " & .Item(intCount)
                            Case 2
                                lblInfo3.Text = dtDItem.Columns(intCount).Caption & " : " & .Item(intCount)
                            Case 3
                                lblInfo4.Text = dtDItem.Columns(intCount).Caption & " : " & .Item(intCount)
                            Case 4
                                lblInfo5.Text = dtDItem.Columns(intCount).Caption & " : " & .Item(intCount)
                            Case 5 'LABLE FOR SALE RATE
                                If Not IsNothing(fgItems.Item(fgItems.Row, "TAX")) AndAlso Trim(fgItems.Item(fgItems.Row, "TAX")) <> "" AndAlso fgItems.Item(fgItems.Row, "TAX") > 0 Then
                                    'lblInfo6.Text = dtDItem.Columns(intCount).Caption & "(+ Excl.) : " & .Item(intCount)
                                    lblInfo6.Text = dtDItem.Columns(intCount).Caption & "(+ Excl.) : " & fgItems.Item(fgItems.RowSel, "RATE")
                                Else
                                    lblInfo6.Text = dtDItem.Columns(intCount).Caption & " : " & .Item(intCount)
                                End If

                            Case 6 'LABLE FOR PROFIT
                                If ConfigurationManager.AppSettings("SaleProfit") = "Yes" Then    'Divya@31/03/08 : Condition checked for User Customize Setting    
                                    'lblInfo7.Text = dtDItem.Columns(intCount).Caption & " : " & .Item(intCount)

                                    lblInfo7.Text = dtDItem.Columns(intCount).Caption & " : " & fgItems.Item(fgItems.RowSel, "RATE") - fgItems.Item(fgItems.RowSel, "PURCHASEPRICE")


                                End If
                            Case 7
                                lblInfo8.Text = dtDItem.Columns(intCount).Caption & " : " & .Item(intCount)
                            Case 8 'LABLE FOR SALE LOOSE
                                If Not dtDItem.Rows(0).Item("Sell Loose") Then
                                    lblInfo9.Text = "Don't Sale this Item Loose."
                                End If
                            Case 9
                                lblInfo10.Text = dtDItem.Columns(intCount).Caption & " : " & .Item(intCount)
                            Case 10 'LABLE FOR SCHEME
                                If Not dtDItem.Rows(0).Item("Scheme On Batch") Is Nothing AndAlso dtDItem.Rows(0).Item("Scheme On Batch") <> 0 AndAlso dtDItem.Rows(0).Item("Scheme On Batch").ToString <> "" AndAlso BScheme.IsValidScheme(dtDItem.Rows(0).Item("Scheme On Batch")) Then
                                    Dim Scheme As CScheme = BScheme.GetScheme(dtDItem.Rows(0).Item("Scheme On Batch"))
                                    lblInfo11.Text = BScheme.GetSchemeName(Scheme)
                                    Scheme = Nothing
                                    '.Item(intCount) = Scheme.GetSchemeName()
                                    'lblInfo11.Text = dtDItem.Columns(intCount).Caption & " : " & .Item(intCount)
                                End If
                        End Select
                    Next
                End With
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "ShowItemInfo")
        End Try
    End Sub
    Private Sub ClearItemInfo()
        Try
            lblInfo1.Text = ""
            lblInfo2.Text = ""
            lblInfo3.Text = ""
            lblInfo4.Text = ""
            lblInfo5.Text = ""
            lblInfo6.Text = ""
            lblInfo7.Text = ""
            lblInfo8.Text = ""
            lblInfo9.Text = ""
            lblInfo10.Text = ""
            lblInfo11.Text = ""
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "ClearItemInfo")
        End Try
    End Sub

    Private Sub CopyItemRow(ByVal FromRowNo As Integer, ByVal ToRowNo As Integer)
        Try
            With fgItems
                .Item(ToRowNo, "ITEMID") = .Item(FromRowNo, "ITEMID")
                .Item(ToRowNo, "CODE") = .Item(FromRowNo, "CODE")
                .Item(ToRowNo, "ITEMNAME") = .Item(FromRowNo, "ITEMNAME")
                .Item(ToRowNo, "COMPANY") = .Item(FromRowNo, "COMPANY")
                .Item(ToRowNo, "LOCATION") = .Item(FromRowNo, "LOCATION")
                '.Item(ToRowNo, "SCHEMEID") = .Item(FromRowNo, "SCHEMEID")
                '.Item(ToRowNo, "SCHEME") = .Item(FromRowNo, "SCHEME")
                .Item(ToRowNo, "STATUS") = .Item(FromRowNo, "STATUS")
                .Item(ToRowNo, "SCHEDULEDRUG") = .Item(FromRowNo, "SCHEDULEDRUG")
                .Item(ToRowNo, "EMERGENCYSTOCK") = .Item(FromRowNo, "EMERGENCYSTOCK")
                .Item(ToRowNo, "TOTALSTOCK") = .Item(FromRowNo, "TOTALSTOCK")
                .Item(ToRowNo, "ISMULTIBATCH") = .Item(FromRowNo, "ISMULTIBATCH")
            End With
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "CopyItemRow")
        End Try
    End Sub


#Region "ONLY FOR REGULAR SALE FORM"

    Private Sub SetDisc(ByVal CallFrom As Char)
        Try
            If CallFrom = "P" Then
                If Trim(Me.txtDisPercent.Text) = "" Then
                    Me.txtDisPercent.Text = "0.00"
                    Me.txtDiscount.Text = "0.00"
                    Me.txtNetAmount.Text = Format(Convert.ToDouble(Me.txtTotal.Text.ToString()), "0.00")
                ElseIf Trim(Me.txtDiscount.Text) = "" Then
                    Me.txtDisPercent.Text = "0.00"
                    Me.txtDiscount.Text = "0.00"
                    Me.txtNetAmount.Text = Format(Convert.ToDouble(Me.txtTotal.Text.ToString()), "0.00")
                ElseIf ValidateDiscount(CallFrom) = 0 Then
                    Me.txtDisPercent.Focus()
                    Exit Sub
                Else
                    Me.txtDiscount.Text = BCALC.GetDiscount(txtTotal.Text, Me.txtDisPercent.Text, "P")
                    Me.txtNetAmount.Text = Format(Convert.ToDouble(Me.txtTotal.Text) - Convert.ToDouble(Me.txtDiscount.Text), "0.00")

                End If
            ElseIf CallFrom = "A" Then
                If Trim(Me.txtDiscount.Text) = "" Then
                    Me.txtDiscount.Text = "0.00"
                    Me.txtNetAmount.Text = Format(Convert.ToDouble(Me.txtTotal.Text.ToString()), "0.00")
                    Me.txtDisPercent.Text = "0.00"
                ElseIf Me.txtDisPercent.Text = "" Then
                    Me.txtDisPercent.Text = "0.00"
                    Me.txtDiscount.Text = "0.00"
                    Me.txtNetAmount.Text = Format(Convert.ToDouble(Me.txtTotal.Text.ToString()), "0.00")
                ElseIf Convert.ToDouble(Me.txtDiscount.Text) >= Convert.ToDouble(Me.txtTotal.Text) And Convert.ToDouble(Me.txtTotal.Text) <> 0 Then
                    BCommon.ShowMsgError(10340)
                    Me.txtDiscount.Text = 0
                    Me.txtDiscount.Focus()
                    Exit Sub
                Else
                    Me.txtDisPercent.Text = BCALC.GetDiscount(txtTotal.Text, Me.txtDiscount.Text, "A")
                    Me.txtNetAmount.Text = Format(Convert.ToDouble(Me.txtTotal.Text) - Convert.ToDouble(Me.txtDiscount.Text), "0.00")
                End If
            End If
            If Me.txtPaidAmt.Text > Me.txtNetAmount.Text Then
                Me.txtPaidAmt.Text = Me.txtNetAmount.Text
            End If
            Call CalculateReturnAmt()
            Call CalculateProfitAmt()
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "SetDisc")
        End Try
    End Sub

    Private Function ValidateDiscount(ByVal validateFor As Char) As Byte
        Dim dobPercent As Double = 0.0
        Try
            If validateFor = "P" Then
                dobPercent = Convert.ToDouble(Me.txtDisPercent.Text.ToString())

                If dobPercent >= 100 Then
                    BCommon.ShowMsgError(10346)
                    Return 0
                ElseIf dobPercent < 0 Then
                    BCommon.ShowMsgError(10114)
                    Return 0
                Else : Return 1
                End If
            Else

            End If

        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "ValidateDiscount()")
        End Try
    End Function
    Private Sub CalculteTotalAmt()
        Try
            Dim intCount As Integer
            TotAmount = 0.0
            For intCount = 1 To fgItems.Rows.Count
                If CDbl(fgItems.Cols("AMOUNT").Item(intCount)) = 0.0 Then Exit For
                TotAmount = TotAmount + fgItems.Cols("AMOUNT").Item(intCount)
            Next
            ' 'Stored all sequence id of frmsale
            ' txtTotal.Text = TotAmount
            txtTotal.Text = checkTextBox(TotAmount)
            txtNetAmount.Text = txtTotal.Text

            txtPaidAmt.Text = 0.0
            txtDiscount.Text = 0.0
            txtDisPercent.Text = 0.0
            txtTax.Text = 0.0
            txtCredit.Text = 0.0
            txtDebit.Text = 0.0
            'MIKE 
            'txtBalance.Text = 0.0
            txtBalance.Text = txtTotal.Text
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "CalculteTotalAmt")
        End Try
    End Sub

    Private Function ValidateData() As Boolean
        Try
            If DateTime.Compare(Me.dtpSaleDate.Value, DateTime.Now()) > 0 Then
                BCommon.ShowMsgError(10228)
                dtpSaleDate.Value = DateTime.Now()
                dtpSaleDate.Focus()
                Return False
            ElseIf ValidateInfo() = False Then
                Return False
            Else
                Return IIf(SetCity(), SetDoctor(), False)
            End If

        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "ValidateData")
            Return False
        End Try
    End Function

    Private Function SetData() As CPerson
        Try
            Dim Person As New CPerson
            Dim Name() As String
            Dim intCount As Integer

            With Person
                .Title = cmbTitle.SelectedValue.ToString
                Name = cmDCustomerName.Text.Split(" ")
                For intCount = 0 To Name.Length - 1
                    If intCount = 0 Then
                        .First_Name = Name(intCount)
                    ElseIf intCount = 1 Then
                        .Middle_Name = Name(intCount)
                    ElseIf intCount = 2 Then
                        .Last_Name = Name(intCount)
                    End If
                Next
                .First_Name = IIf(.First_Name = Nothing, "", .First_Name)
                .Middle_Name = IIf(.Middle_Name = Nothing, "", .Middle_Name)
                .Last_Name = IIf(.Last_Name = Nothing, "", .Last_Name)
            End With
            Return Person
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "SetData")
            Return Nothing
        End Try
    End Function

    Private Function GetDeletedItems() As String
        Try
            Dim intCount As Integer
            Dim strItems As String = ""
            With fgItems
                For intCount = 1 To fgItems.Rows.Count - 1
                    If Not (.Item(intCount, 0) = Nothing OrElse .Item(intCount, 0).ToString() = "") Then
                        strItems = strItems & .Item(intCount, "SEQID")    '
                        strItems = strItems & ","
                        'intRows(i) = intCount
                    Else : Exit For
                    End If
                Next
                If strItems.Length > 0 Then strItems = strItems.Remove(strItems.Length - 1, 1)
                Return strItems
            End With
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "GetDeletedItems")
            Return Nothing
        End Try
    End Function

    Private Function GetNewAddedItems() As String
        Try
            Dim strItems As New StringBuilder
            Dim TotalItems As String = GetDeletedItems()
            If TotalItems <> String.Empty AndAlso strExistingItems <> String.Empty Then
                Dim Items As String() = TotalItems.Split(",")
                For intCount As Integer = 0 To Items.Length - 1
                    If InStr(strExistingItems, Items(intCount)) <= 0 Then  'ITEM IS NEWLLY ADDED
                        strItems.Append(Items(intCount).ToString() & ",")
                    Else 'ITEM IS FROM COUNTER SALE
                    End If
                Next
                If strItems.Length > 0 Then
                    strItems.Replace(",", "", strItems.Length - 1, 1)
                End If
                Return strItems.ToString()
            End If
            Return strItems.ToString()
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "GetNewAddedItems")
            Return String.Empty
        End Try
    End Function

    Private Function setCalcData() As CtaxCalculation
        Dim salePrint As New CSalePrint
        Dim taxCalc As New CtaxCalculation

        Try
            With taxCalc
                .TotalVal = checkTextBox(txtTotal.Text)
                .DiscountVal = checkTextBox(txtDiscount.Text)
                '.TaxVal = checkTextBox(txtTax.Text)
                '.CreditVal = checkTextBox(txtCredit.Text)
                '.DebitVal = checkTextBox(txtDebit.Text)
                .PaidVal = checkTextBox(txtPaidAmt.Text)
                .BalanceVal = checkTextBox(txtBalance.Text)
            End With

            salePrint.TaxCalculation = taxCalc

            Return taxCalc
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "setCalcData")
            Return Nothing
        End Try
    End Function

    Private Function checkTextBox(ByVal txtBox As String)
        Try
            If txtBox = "" Then
                Return 0.0
            Else
                Return Format(CType(txtBox, Double), "0.00")
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "checkTextBox")
            Return Nothing
        End Try
    End Function

    Private Sub GetCalculation()
        Try

            '  Dim dblBalance As Double
            Dim TaxCal As CtaxCalculation
            TaxCal = setCalcData()

            'txtNetAmount.Text = Format(TaxCal.GrossAmount, "0.00")
            'txtPaidAmt.Text = Format(TaxCal.GrossAmount, "0.00")
            'txtBalance.Text = "0.00"

            'Modified By:-VINIT(2008/01/14)
            txtNetAmount.Text = Format(TaxCal.TotalVal - TaxCal.DiscountVal, "0.00")
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "GetCalculation")
        End Try
    End Sub


    Private Sub CalculateReturnAmt()
        Dim dblPaidAmount As Double = 0
        Dim dblGrossAmt As Double = 0
        Try
            If Me.txtPaidAmt.Text <> "" Then
                dblPaidAmount = Convert.ToDouble(Me.txtPaidAmt.Text.ToString())
            Else
                dblPaidAmount = 0.0
                Me.txtPaidAmt.Text = "0.00"
            End If
            'Modified By:-VINIT(2008/01/14)
            'After Discussion with Micheal
            'Paid Amount Should be compare with GrossAmount
            If Me.txtNetAmount.Text <> "" Then
                dblGrossAmt = Convert.ToDouble(Me.txtNetAmount.Text.ToString())
            Else
                dblGrossAmt = 0.0
            End If

            If dblPaidAmount > dblGrossAmt Then
                BCommon.ShowMsgError(10171)
                Me.txtPaidAmt.Text = Format(dblGrossAmt, "0.00")
                Me.txtBalance.Text = Format((dblGrossAmt - Convert.ToDouble(Me.txtPaidAmt.Text.ToString())), "0.00")
            Else
                Me.txtBalance.Text = Format((dblGrossAmt - dblPaidAmount), "0.00")
            End If

        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "CalculateReturnAmt")
        End Try
    End Sub

    Private Sub CalculateAmt()
        Dim intCount As Integer
        Try
            With fgItems
                TotAmount = 0.0

                If IsNothing(.Item(.Row, .Col)) OrElse Trim(.Item(.Row, .Col)) = "" Then
                    txtTotal.Text = "0.00"
                    txtPaidAmt.Text = "0.00"
                    txtTax.Text = "0.00"
                    txtDiscount.Text = "0.00"
                    txtNetAmount.Text = "0.00"
                    txtBalance.Text = "0.00"
                    Exit Sub
                End If
                SetItemAmount(.Row) ' = Format(CDbl(.Cols("QTY").Item(.Row)) * CDbl(.Cols("RATE").Item(.Row)), "0.00")

                For intCount = 1 To .Rows.Count - 1
                    If CDbl(.Cols("AMOUNT").Item(intCount)) = 0.0 Then Exit For

                    If .Item(intCount, "STATUS") = "A" OrElse .Item(intCount, "STATUS") = "W" OrElse .Item(intCount, "STATUS") = "U" Then
                        TotAmount = TotAmount + CDbl(.Cols("AMOUNT").Item(intCount))
                    End If
                Next
                'PANKAJ@20071130: Comment Existing and show only total. -----
                'txtNetAmount.Text = Format(TotAmount, "0.00")
                'txtPaidAmt.Text = Format(TotAmount, "0.00")

                txtTotal.Text = Format(TotAmount, "0.00") 'Chandrakant
                'Modified By:-VINIT(2008/01/14)
                'Initially TotalAmount and GrossAmount will be calculated.
                txtNetAmount.Text = Format(TotAmount, "0.00")

                GetCalculation()
                Call CalculateReturnAmt()
                ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
            End With
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "CalculateAmt")
        End Try
    End Sub

    Private Function SetCity() As Boolean
        Dim ChkCity As Byte = 0
        Try
            Dim dtCity As DataTable = DAddress.change_state(BCommon.GetConfigValues("State"), BCommon.GetConfigValues("Country"))

            If Trim(txtAddress.Text) <> "" Then

                For Each drCity As DataRow In dtCity.Select("Description = '" & txtAddress.Text & "'")
                    intCityCD = drCity("CityCD").ToString
                    ChkCity = 1
                Next
                If ChkCity = 0 Then intCityCD = DAddress.SaveCity(BCommon.GetConfigValues("State"), BCommon.GetConfigValues("Country"), txtAddress.Text, 0)

                Return True

            Else 'If Trim(txtAddress.Text) = "" Then
                BCommon.ShowMsgError(10310)
                txtAddress.Focus()
                txtAddress.Text = ""
                Return False
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "SetCity")
        End Try
    End Function

    Private Function SetDoctor() As Boolean
        Dim Personid As Integer
        Dim DoctName() As String
        Try

            If Not IsNothing(cmDDoctor.SelectedValue) AndAlso cmDDoctor.SelectedValue > 0 Then
                DoctorID = cmDDoctor.SelectedValue
                Return True
            Else
                If UCase(cmDDoctor.Text) = "" Then
                    BCommon.ShowMsgError(10319)
                    cmDDoctor.Focus()
                    Return False
                Else
                    Dim Doctor As New CDoctor
                    Dim DoctPerson As New CPerson
                    DoctName = cmDDoctor.Text.Split(" ")
                    With DoctPerson
                        .Title = IIf(.Title = Nothing, "MR", "")
                        For intCount As Integer = 0 To DoctName.Length - 1
                            If intCount = 0 Then
                                .First_Name = DoctName(intCount)
                            ElseIf intCount = 1 Then
                                .Middle_Name = DoctName(intCount)
                            ElseIf intCount = 2 Then
                                .Last_Name = DoctName(intCount)
                            End If
                        Next
                        .First_Name = IIf(.First_Name = Nothing, "", .First_Name)
                        .Middle_Name = IIf(.Middle_Name = Nothing, "", .Middle_Name)
                        .Last_Name = IIf(.Last_Name = Nothing, "", .Last_Name)
                    End With
                    'Personid = DDoctor.SaveNewPerson(Doctor, DoctPerson, "DOCTOR")
                    DoctorID = Doctor.doctorID
                    BtLoading = 0
                    'BCommon.SetComboValues(cmDDoctor, DDoctor.GetDoctorList(), "DoctorID", "Name")
                    'cmDDoctor.SelectedValue = DoctorID
                    BtLoading = 1
                    Return True

                End If
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "SetDoctor")
        End Try
    End Function

    '***********************************************
    'Calculate Net Profit or Loss
    '============================
    Private Sub CalculateProfitAmt()
        Dim intCount As Integer
        Dim dobProfit As Double = 0.0
        Try
            With fgItems
                Dim dobTotPurAmount As Double = 0.0
                For intCount = 1 To .Rows.Count - 1
                    If IsNothing(.Cols("ITEMID").Item(intCount)) OrElse Trim(.Cols("ITEMID").Item(intCount)) = "" Then Exit For
                    dobTotPurAmount += CDbl(.Cols("PURCHASEPRICE").Item(intCount) * .Cols("QTY").Item(intCount))
                Next

                'Modified By:-VINIT(2008/03/14)
                'When Total Item PurchasePrice is zero then total amount will be profit.
                If dobTotPurAmount = 0 Then
                    If Me.txtNetAmount.Text <> "" Then
                        dobProfit = CDbl(Me.txtNetAmount.Text.ToString()) - dobTotPurAmount
                    End If
                ElseIf dobTotPurAmount > 0 Then
                    If Me.txtNetAmount.Text <> "" Then
                        dobProfit = CDbl(Me.txtNetAmount.Text.ToString()) - dobTotPurAmount
                    End If
                End If
                'txtProfit.Text = Format(dobProfit, "0.00")

                If dobProfit >= 0 Then
                    'Profit :  profit & "Rs"
                    txtProfit.Text = Format(dobProfit, "0.00")
                    Me.lblProLoss.Text = "Profit"
                Else
                    'Loss :  profit & "Rs"
                    txtProfit.Text = Format(dobProfit, "0.00")
                    Me.lblProLoss.Text = "Loss"
                End If
            End With
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "CalculateAmt")
        End Try
    End Sub
#End Region '"ONLY FOR REGULAR SALE FORM"

#End Region '"USER DEFINED FUNCITONS"

#Region "PRINT BILL REPORT"

    Public Sub PrintFinalBIll()
        Dim Layoutid As Integer
        'VINIT
        Dim PWi As Double
        Dim Ps As PaperSize
        Dim dtGetData As New DataTable

        Try

            Layoutid = BCommon.GetPrefValue("SALEBILLLAYOUT")
            If Layoutid <= 0 Then
                BCommon.ShowMsgError(10338)
                Exit Sub
            End If
            dtGetData = DDocument.GetData(Layoutid)
            If dtGetData.Rows.Count > 0 Then
                With PrintDocument1.DefaultPageSettings
                    PHi = (dtGetData.Rows(0).Item("Height") * 100)
                    PWi = (dtGetData.Rows(0).Item("Width") * 100)
                    Ps = New PaperSize("Cust", PWi, PHi)

                    .Margins.Top = (dtGetData.Rows(0).Item("TopM") * 100)
                    .Margins.Bottom = (dtGetData.Rows(0).Item("BottomM") * 100)
                    .Margins.Left = (dtGetData.Rows(0).Item("LeftM") * 100)
                    .Margins.Right = (dtGetData.Rows(0).Item("RightM") * 100)
                    .PaperSize = Ps


                End With
            End If
            '>>>>>>>>END:-VINIT(20080103)

            headfont = New Font("MS Serif", 12, FontStyle.Bold)
            tableFont = New Font("MS Serif", 8)
            titlefont = New Font("MS Serif", 9)
            tabletitlefont = New Font("MS Serif", 8, FontStyle.Bold)

            X1 = PrintDocument1.DefaultPageSettings.Margins.Left

            With PrintDocument1.DefaultPageSettings
                pageWidth = .PaperSize.Width - .Margins.Left - .Margins.Right
            End With

            X2 = X1 + 120
            X3 = X2 + pageWidth * 0.5

            'COLLECT THE FOOTER LINES 
            Foot1 = BCommon.GetPrefValue("SALEFOOT1")
            Foot2 = BCommon.GetPrefValue("SALEFOOT2")
            Foot3 = BCommon.GetPrefValue("SALEFOOT3")

            'IF U WANT TO PRINT DIRECTLY THEN
            '    PrintDocument1.Print()
            'ELSEIF U WANT PRINT AFTER PRINT PREVIEW THEN U PLS USE THIS CODE


            If ConfigurationManager.AppSettings("Mode").ToString() = "D" Then
                PrintPreviewDialog1.Document = PrintDocument1
                'Divya @ 14/03/2008
                PrintPreviewDialog1.ShowIcon = True
                'Me.PrintPreviewDialog1.Icon = Global.Pharmacy.My.Resources.RxOffice1Icon32x32
                '>>End
                PrintPreviewDialog1.ShowDialog()
            Else
                PrintDocument1.Print()
            End If

        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "PrintFinalBIll")
        End Try
    End Sub
    Private Function GetFooterHeight(ByVal e As System.Drawing.Printing.PrintPageEventArgs) As Integer
        Dim TextSize As New System.Drawing.SizeF
        Dim TotFooterHieght As Integer
        If e.HasMorePages = False Then
            TextSize = e.Graphics.MeasureString("Pharmacist", titlefont)
            '3 Footer Line And One Total Amount Line 
            TotFooterHieght = TextSize.Height * 5
        Else
            TextSize = e.Graphics.MeasureString("...Cotinued", titlefont)
            '3 Footer Line And One Total Amount Line 
            TotFooterHieght = TextSize.Height * 5
        End If
        Return TotFooterHieght
    End Function

    Private Sub SetPageHeader(ByVal e As System.Drawing.Printing.PrintPageEventArgs)
        Dim X As Integer
        Dim dtFirm As New DataTable
        Dim TextSize As New System.Drawing.SizeF
        Dim XStart As Integer
        Dim fmtr As New StringFormat(StringFormatFlags.NoClip)
        Dim fmtalign As New StringFormat(fmtr)

        Try
            dtFirm = BCommon.FirmInfo()
            With PrintDocument1.DefaultPageSettings
                X = .PaperSize.Width - .Margins.Left - .Margins.Right
            End With

            If PageNo > 1 Then 'For Next Pages in Same Bill Page No print instead of Date
                TextSize = e.Graphics.MeasureString("Date: dd/MM/yy", titlefont)
                XStart = X - (TextSize.Width + 10)
            Else
                'HEADER STATIC
                TextSize = e.Graphics.MeasureString("Date: dd/MM/yy", titlefont)
                XStart = X - (TextSize.Width + 10)
            End If
            fmtalign.Alignment = StringAlignment.Far
            If dtFirm.Rows.Count > 0 Then
                TextSize = e.Graphics.MeasureString(Trim(dtFirm.Rows(0).Item("FirmName").ToString()), headfont)
                e.Graphics.DrawString(Trim(dtFirm.Rows(0).Item("FirmName").ToString()), headfont, Brushes.Black, DrawRectangelF(X1, curY, XStart, TextSize.Height))
                If PageNo > 1 Then
                    TextSize = e.Graphics.MeasureString("Date: dd/MM/yy", titlefont)
                    e.Graphics.DrawString("Page No : " & PageNo, titlefont, Brushes.Black, DrawRectangelF(XStart + X1, curY, TextSize.Width + 10, TextSize.Height), fmtalign)
                Else
                    TextSize = e.Graphics.MeasureString("Date: dd/MM/yy", titlefont)
                    e.Graphics.DrawString("Date:" & Format(Now, "dd/MM/yy"), titlefont, Brushes.Black, DrawRectangelF(XStart + X1, curY, TextSize.Width + 10, TextSize.Height), fmtalign)
                End If

                'Text Size Set to Height of FirmName.
                TextSize = e.Graphics.MeasureString(Trim(dtFirm.Rows(0).Item("FirmName").ToString()), headfont)
                curY = curY + TextSize.Height

                e.Graphics.DrawString(Trim(dtFirm.Rows(0).Item("addDesc1").ToString()) & "," & Trim(dtFirm.Rows(0).Item("Description").ToString()) & "-" & Trim(dtFirm.Rows(0).Item("PinCode").ToString()) & ", Tel: " & Trim(dtFirm.Rows(0).Item("phone1").ToString()), titlefont, Brushes.Black, X1, curY)
                'e.Graphics.DrawString("Bill No:" & txtVoucher.Text, titlefont, Brushes.Black, DrawRectangelF(XStart, curY, XStart, TextSize.Height))
                TextSize = e.Graphics.MeasureString(Trim(dtFirm.Rows(0).Item("addDesc1").ToString()) & "," & Trim(dtFirm.Rows(0).Item("Description").ToString()) & "-" & Trim(dtFirm.Rows(0).Item("PinCode").ToString()) & ", Tel: " & Trim(dtFirm.Rows(0).Item("phone1").ToString()), titlefont)

                curY = curY + TextSize.Height

            Else  'IF FIRM INFORMATION NOT FOUND
                If PageNo > 1 Then 'Pankaj
                    TextSize = e.Graphics.MeasureString("Date: dd/MM/yy", titlefont)
                    e.Graphics.DrawString("", headfont, Brushes.Black, DrawRectangelF(X1, curY, XStart - 10, TextSize.Height))
                    e.Graphics.DrawString("Page No : " & PageNo, titlefont, Brushes.Black, DrawRectangelF(XStart + X1, curY, TextSize.Width + 10, TextSize.Height), fmtalign)
                Else
                    TextSize = e.Graphics.MeasureString("Date: dd/MM/yy", titlefont)
                    e.Graphics.DrawString("", headfont, Brushes.Black, DrawRectangelF(X1, curY, XStart - 10, TextSize.Height))
                    e.Graphics.DrawString("Date:" & Format(Now, "dd/MM/yy"), titlefont, Brushes.Black, DrawRectangelF(XStart + X1, curY, TextSize.Width + 10, TextSize.Height), fmtalign)
                End If
                curY = curY + TextSize.Height
                'e.Graphics.DrawString("", titlefont, Brushes.Black, X1, curY)
                ''e.Graphics.DrawString("Bill No:" & txtVoucher.Text, titlefont, Brushes.Black, DrawRectangelF(XStart, curY, XStart, TextSize.Height))
                'TextSize = e.Graphics.MeasureString("", titlefont)
                'curY = curY + TextSize.Height
            End If

            'HEADER LINE 2  
            If PageNo = 1 Then
                If cmDCustomerName.Text <> "" Then
                    If txtAddress.Text <> "" Then
                        TextSize = e.Graphics.MeasureString("Add : " & txtAddress.Text.ToString(), titlefont)
                    Else
                        TextSize = e.Graphics.MeasureString("Add : XXXXXX", titlefont)
                    End If
                    XStart = X - (TextSize.Width + 10)
                    e.Graphics.DrawString("Patient   : " & cmDCustomerName.Text.ToString(), titlefont, Brushes.Black, DrawRectangelF(X1, curY, XStart, TextSize.Height))
                    If txtAddress.Text <> "" Then
                        e.Graphics.DrawString("Add : " & txtAddress.Text.ToString(), titlefont, Brushes.Black, DrawRectangelF(XStart + X1, curY, TextSize.Width + 10, TextSize.Height), fmtalign)
                    Else
                        e.Graphics.DrawString("Add : ", titlefont, Brushes.Black, DrawRectangelF(XStart + X1, curY, TextSize.Width + 10, TextSize.Height))
                    End If

                    curY = curY + TextSize.Height
                End If
            End If

            'HEADER LINE 3  
            If cmDDoctor.Text <> "" Then
                TextSize = e.Graphics.MeasureString("Bill No:" & txtVoucher.Text, titlefont)
                XStart = X - (TextSize.Width + 10)
                If PageNo = 1 Then
                    e.Graphics.DrawString("Doctor : " & cmDDoctor.Text.ToString(), titlefont, Brushes.Black, DrawRectangelF(X1, curY, XStart, TextSize.Height))
                Else
                    e.Graphics.DrawString("", titlefont, Brushes.Black, DrawRectangelF(X1, curY, XStart, TextSize.Height))
                End If
                'TextSize = e.Graphics.MeasureString("Bill No:" & txtVoucher.Text, titlefont)
                'XStart = X - (TextSize.Width) + 10
                e.Graphics.DrawString("Bill No: " & txtVoucher.Text, titlefont, Brushes.Black, DrawRectangelF(XStart + X1, curY, TextSize.Width + 10, TextSize.Height), fmtalign)
                TextSize = e.Graphics.MeasureString("Doctor : " & cmDDoctor.Text.ToString(), titlefont)
                curY = curY + TextSize.Height
            End If
            'If cmDDoctor.Text <> "" Then
            '    TextSize = e.Graphics.MeasureString("Bill No:" & txtVoucher.Text, titlefont)
            '    XStart = X - (TextSize.Width)
            '    e.Graphics.DrawRectangle(Pens.Black, X1, curY, XStart, TextSize.Height) '--
            '    e.Graphics.DrawString("Doctor : " & cmDDoctor.Text.ToString(), titlefont, Brushes.Black, DrawRectangelF(X1, curY, XStart, TextSize.Height))
            '    e.Graphics.DrawRectangle(Pens.Black, XStart, curY, TextSize.Width, TextSize.Height) '--
            '    e.Graphics.DrawString("Bill No:" & txtVoucher.Text, titlefont, Brushes.Black, DrawRectangelF(XStart, curY, TextSize.Width, TextSize.Height), fmtalign)
            '    TextSize = e.Graphics.MeasureString("Doctor : " & cmDDoctor.Text.ToString(), titlefont)
            '    curY = curY + TextSize.Height
            'End If


            With PrintDocument1.DefaultPageSettings
                e.Graphics.DrawLine(Pens.Black, .Margins.Left, curY, .PaperSize.Width - .Margins.Right, curY)
                'X = .PaperSize.Width - .Margins.Left - .Margins.Right
                wi = X / 20
            End With

            'DESC  +  COMP  +  EXP  + BATCH + QTY  + AMOUNT 
            '  8   +    2   +   1.5   +   3   +   2  +   2
            'Caption of the Print Bill
            '=========================

            e.Graphics.DrawString("Description", tabletitlefont, Brushes.Black, X1, curY)
            e.Graphics.DrawString("Comp", tabletitlefont, Brushes.Black, X1 + (wi * 8), curY)
            e.Graphics.DrawString("Exp", tabletitlefont, Brushes.Black, X1 + (wi * 9.5), curY)
            e.Graphics.DrawString("CLRcode", tabletitlefont, Brushes.Black, X1 + (wi * 11.5), curY)
            e.Graphics.DrawString("Qty", tabletitlefont, Brushes.Black, X1 + (wi * 16), curY)
            e.Graphics.DrawString("Amount", tabletitlefont, Brushes.Black, X1 + (wi * 18), curY)
            TextSize = e.Graphics.MeasureString("Description", tabletitlefont)
            curY = curY + TextSize.Height
            With PrintDocument1.DefaultPageSettings
                e.Graphics.DrawLine(Pens.Black, .Margins.Left, curY, .PaperSize.Width - .Margins.Right, curY)
                FinalSize = Y + 110 + 20
            End With
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "SetPageHeader")
        End Try
    End Sub

    Private Sub SetPageFooter(ByVal e As System.Drawing.Printing.PrintPageEventArgs)
        Dim TextSize As New System.Drawing.SizeF
        Dim FooterRowHieght As Integer
        Dim XStart As Integer
        Dim PWidth As Integer ' Page Width 
        Dim tempstr As String
        Try

            If e.HasMorePages = False Then
                TextSize = e.Graphics.MeasureString("Pharmacist", titlefont)
            Else
                TextSize = e.Graphics.MeasureString("...Cotinued", titlefont)
            End If
            FooterRowHieght = TextSize.Height

            With PrintDocument1.DefaultPageSettings
                e.Graphics.DrawLine(Pens.Black, .Margins.Left, curY, .PaperSize.Width - .Margins.Right, curY)
                PWidth = .PaperSize.Width - .Margins.Right
            End With

            If e.HasMorePages = False Then
                TextSize = e.Graphics.MeasureString("Net Amt : " & ConfigurationManager.AppSettings("Currency") & " " & Me.txtNetAmount.Text.ToString(), titlefont)
                XStart = PWidth - (TextSize.Width + 10)

                'e.Graphics.DrawString("Total : " & ConfigurationManager.AppSettings("Currency") & " " & BCommon.CheckDecimal(dobTotal.ToString()), titlefont, Brushes.Black, (XStart / XStart) + 1, curY)
                'e.Graphics.DrawString("Total : " & ConfigurationManager.AppSettings("Currency") & " " & BCommon.CheckDecimal(dobTotal.ToString()), titlefont, Brushes.Black, (XStart / 5), curY)
                e.Graphics.DrawString("Total :" & ConfigurationManager.AppSettings("Currency") & " " & BCommon.CheckDecimal(dobTotal.ToString()), titlefont, Brushes.Black, X1, curY)

                If txtDiscount.Text <> "" Then
                    e.Graphics.DrawString("Disc : " & ConfigurationManager.AppSettings("Currency") & " " & BCommon.CheckDecimal(Math.Round(CDbl(txtDiscount.Text), 2).ToString()), titlefont, Brushes.Black, (XStart / 2), curY)
                End If
                e.Graphics.DrawString("Net Amt : " & ConfigurationManager.AppSettings("Currency") & " " & BCommon.CheckDecimal(txtNetAmount.Text.ToString()), titlefont, Brushes.Black, XStart, curY)
                curY = curY + FooterRowHieght



                If txtDiscount.Text <> "" Then
                    e.Graphics.DrawString("Paid : " & ConfigurationManager.AppSettings("Currency") & " " & BCommon.CheckDecimal(Math.Round(CDbl(txtPaidAmt.Text), 2).ToString()), titlefont, Brushes.Black, (XStart / 2), curY)
                End If
                TextSize = e.Graphics.MeasureString("Bal Amt : " & ConfigurationManager.AppSettings("Currency") & " " & Me.txtNetAmount.Text.ToString(), titlefont)
                XStart = PWidth - (TextSize.Width + 10)

                e.Graphics.DrawString("Bal Amt : " & ConfigurationManager.AppSettings("Currency") & " " & BCommon.CheckDecimal(txtBalance.Text.ToString()), titlefont, Brushes.Black, XStart, curY)
                curY = curY + FooterRowHieght
                dobTotal = 0.0 'ReSet dobTotal to 0 because it is globaly defined.
            End If

            With PrintDocument1.DefaultPageSettings
                e.Graphics.DrawLine(Pens.Black, .Margins.Left, curY, .PaperSize.Width - .Margins.Right, curY)
            End With

            If e.HasMorePages = False Then
                '*********FOOTER SECTION
                'FOOTER LINE 1
                tempstr = "For " & BCommon.GetFirmFullName
                TextSize = e.Graphics.MeasureString(tempstr, titlefont)
                XStart = PWidth - (TextSize.Width + 10)
                e.Graphics.DrawString(Foot1, titlefont, Brushes.Black, DrawRectangelF(X1, curY, XStart - 10, FooterRowHieght))
                e.Graphics.DrawString(tempstr, titlefont, Brushes.Black, DrawRectangelF(XStart, curY, TextSize.Width + 10, FooterRowHieght))
                curY = curY + FooterRowHieght
                'FOOTER LINE 2
                e.Graphics.DrawString(Foot2, titlefont, Brushes.Black, X1, curY)
                curY = curY + FooterRowHieght
                'FOOTER LINE 3
                tempstr = "Pharmacist"
                TextSize = e.Graphics.MeasureString(tempstr, titlefont)
                XStart = PWidth - (TextSize.Width + 10)
                e.Graphics.DrawString(Foot3, titlefont, Brushes.Black, DrawRectangelF(X1, curY, XStart - 10, FooterRowHieght))
                e.Graphics.DrawString(tempstr, titlefont, Brushes.Black, DrawRectangelF(XStart, curY, XStart, FooterRowHieght))
            Else
                TextSize = e.Graphics.MeasureString("...Continued", titlefont)
                XStart = PWidth - (TextSize.Width + 10)
                curY = curY + TextSize.Height
                e.Graphics.DrawString("...Cotinued", titlefont, Brushes.Black, DrawRectangelF(XStart, curY, TextSize.Width, FooterRowHieght))
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "SetPageFooter")
        End Try
    End Sub
#End Region '"PRINT BILL REPORT"

    Private Sub PrintPreviewDialog1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles PrintPreviewDialog1.FormClosing
        IsBillSaved = 1
    End Sub

End Class